1// Copyright 2012-present Oliver Eilhard. All rights reserved. 2// Use of this source code is governed by a MIT-license. 3// See http://olivere.mit-license.org/license.txt for details. 4 5package elastic 6 7import ( 8 "context" 9 "encoding/json" 10 "testing" 11) 12 13func TestMoreLikeThisQuerySourceWithLikeText(t *testing.T) { 14 q := NewMoreLikeThisQuery().LikeText("Golang topic").Field("message") 15 src, err := q.Source() 16 if err != nil { 17 t.Fatal(err) 18 } 19 data, err := json.Marshal(src) 20 if err != nil { 21 t.Fatal(err) 22 } 23 got := string(data) 24 expected := `{"more_like_this":{"fields":["message"],"like":["Golang topic"]}}` 25 if got != expected { 26 t.Fatalf("expected\n%s\n,got:\n%s", expected, got) 27 } 28} 29 30func TestMoreLikeThisQuerySourceWithLikeAndUnlikeItems(t *testing.T) { 31 q := NewMoreLikeThisQuery() 32 q = q.LikeItems( 33 NewMoreLikeThisQueryItem().Id("1"), 34 NewMoreLikeThisQueryItem().Index(testIndexName2).Type("comment").Id("2").Routing("routing_id"), 35 ) 36 q = q.IgnoreLikeItems(NewMoreLikeThisQueryItem().Id("3")) 37 src, err := q.Source() 38 if err != nil { 39 t.Fatal(err) 40 } 41 data, err := json.Marshal(src) 42 if err != nil { 43 t.Fatal(err) 44 } 45 got := string(data) 46 expected := `{"more_like_this":{"like":[{"_id":"1"},{"_id":"2","_index":"elastic-test2","_routing":"routing_id","_type":"comment"}],"unlike":[{"_id":"3"}]}}` 47 if got != expected { 48 t.Fatalf("expected\n%s\n,got:\n%s", expected, got) 49 } 50} 51 52func TestMoreLikeThisQuery(t *testing.T) { 53 client := setupTestClientAndCreateIndex(t) 54 55 tweet1 := tweet{User: "olivere", Message: "Welcome to Golang and Elasticsearch."} 56 tweet2 := tweet{User: "olivere", Message: "Another Golang topic."} 57 tweet3 := tweet{User: "sandrae", Message: "Cycling is fun."} 58 59 // Add all documents 60 _, err := client.Index().Index(testIndexName).Type("doc").Id("1").BodyJson(&tweet1).Do(context.TODO()) 61 if err != nil { 62 t.Fatal(err) 63 } 64 65 _, err = client.Index().Index(testIndexName).Type("doc").Id("2").BodyJson(&tweet2).Do(context.TODO()) 66 if err != nil { 67 t.Fatal(err) 68 } 69 70 _, err = client.Index().Index(testIndexName).Type("doc").Id("3").BodyJson(&tweet3).Do(context.TODO()) 71 if err != nil { 72 t.Fatal(err) 73 } 74 75 _, err = client.Flush().Index(testIndexName).Do(context.TODO()) 76 if err != nil { 77 t.Fatal(err) 78 } 79 80 // Common query 81 mltq := NewMoreLikeThisQuery().LikeText("Golang topic").Field("message") 82 res, err := client.Search(). 83 Index(testIndexName). 84 Query(mltq). 85 Do(context.TODO()) 86 if err != nil { 87 t.Fatal(err) 88 } 89 if res.Hits == nil { 90 t.Errorf("expected SearchResult.Hits != nil; got nil") 91 } 92} 93