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 TestSimpleQueryStringQuery(t *testing.T) { 14 q := NewSimpleQueryStringQuery(`"fried eggs" +(eggplant | potato) -frittata`) 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.Fatalf("marshaling to JSON failed: %v", err) 22 } 23 got := string(data) 24 expected := `{"simple_query_string":{"query":"\"fried eggs\" +(eggplant | potato) -frittata"}}` 25 if got != expected { 26 t.Errorf("expected\n%s\n,got:\n%s", expected, got) 27 } 28} 29 30func TestSimpleQueryStringQueryExec(t *testing.T) { 31 // client := setupTestClientAndCreateIndexAndLog(t, SetTraceLog(log.New(os.Stdout, "", 0))) 32 client := setupTestClientAndCreateIndex(t) 33 34 tweet1 := tweet{User: "olivere", Message: "Welcome to Golang and Elasticsearch."} 35 tweet2 := tweet{User: "olivere", Message: "Another unrelated topic."} 36 tweet3 := tweet{User: "sandrae", Message: "Cycling is fun."} 37 38 // Add all documents 39 _, err := client.Index().Index(testIndexName).Type("tweet").Id("1").BodyJson(&tweet1).Do(context.TODO()) 40 if err != nil { 41 t.Fatal(err) 42 } 43 44 _, err = client.Index().Index(testIndexName).Type("tweet").Id("2").BodyJson(&tweet2).Do(context.TODO()) 45 if err != nil { 46 t.Fatal(err) 47 } 48 49 _, err = client.Index().Index(testIndexName).Type("tweet").Id("3").BodyJson(&tweet3).Do(context.TODO()) 50 if err != nil { 51 t.Fatal(err) 52 } 53 54 _, err = client.Flush().Index(testIndexName).Do(context.TODO()) 55 if err != nil { 56 t.Fatal(err) 57 } 58 59 // Match all should return all documents 60 searchResult, err := client.Search(). 61 Index(testIndexName). 62 Query(NewSimpleQueryStringQuery("+Golang +Elasticsearch")). 63 Do(context.TODO()) 64 if err != nil { 65 t.Fatal(err) 66 } 67 if searchResult.Hits == nil { 68 t.Errorf("expected SearchResult.Hits != nil; got nil") 69 } 70 if searchResult.Hits.TotalHits != 1 { 71 t.Errorf("expected SearchResult.Hits.TotalHits = %d; got %d", 1, searchResult.Hits.TotalHits) 72 } 73 if len(searchResult.Hits.Hits) != 1 { 74 t.Errorf("expected len(SearchResult.Hits.Hits) = %d; got %d", 1, len(searchResult.Hits.Hits)) 75 } 76 77 for _, hit := range searchResult.Hits.Hits { 78 if hit.Index != testIndexName { 79 t.Errorf("expected SearchResult.Hits.Hit.Index = %q; got %q", testIndexName, hit.Index) 80 } 81 item := make(map[string]interface{}) 82 err := json.Unmarshal(*hit.Source, &item) 83 if err != nil { 84 t.Fatal(err) 85 } 86 } 87} 88