search_queries_common_terms_test.go 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  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. package elastic
  5. import (
  6. "context"
  7. "encoding/json"
  8. _ "net/http"
  9. "testing"
  10. )
  11. func TestCommonTermsQuery(t *testing.T) {
  12. q := NewCommonTermsQuery("message", "Golang").CutoffFrequency(0.001)
  13. src, err := q.Source()
  14. if err != nil {
  15. t.Fatal(err)
  16. }
  17. data, err := json.Marshal(src)
  18. if err != nil {
  19. t.Fatalf("marshaling to JSON failed: %v", err)
  20. }
  21. got := string(data)
  22. expected := `{"common":{"message":{"cutoff_frequency":0.001,"query":"Golang"}}}`
  23. if got != expected {
  24. t.Errorf("expected\n%s\n,got:\n%s", expected, got)
  25. }
  26. }
  27. func TestSearchQueriesCommonTermsQuery(t *testing.T) {
  28. client := setupTestClientAndCreateIndex(t)
  29. tweet1 := tweet{User: "olivere", Message: "Welcome to Golang and Elasticsearch."}
  30. tweet2 := tweet{User: "olivere", Message: "Another unrelated topic."}
  31. tweet3 := tweet{User: "sandrae", Message: "Cycling is fun."}
  32. // Add all documents
  33. _, err := client.Index().Index(testIndexName).Type("tweet").Id("1").BodyJson(&tweet1).Do(context.TODO())
  34. if err != nil {
  35. t.Fatal(err)
  36. }
  37. _, err = client.Index().Index(testIndexName).Type("tweet").Id("2").BodyJson(&tweet2).Do(context.TODO())
  38. if err != nil {
  39. t.Fatal(err)
  40. }
  41. _, err = client.Index().Index(testIndexName).Type("tweet").Id("3").BodyJson(&tweet3).Do(context.TODO())
  42. if err != nil {
  43. t.Fatal(err)
  44. }
  45. _, err = client.Flush().Index(testIndexName).Do(context.TODO())
  46. if err != nil {
  47. t.Fatal(err)
  48. }
  49. // Common terms query
  50. q := NewCommonTermsQuery("message", "Golang")
  51. searchResult, err := client.Search().Index(testIndexName).Query(q).Do(context.TODO())
  52. if err != nil {
  53. t.Fatal(err)
  54. }
  55. if searchResult.Hits == nil {
  56. t.Errorf("expected SearchResult.Hits != nil; got nil")
  57. }
  58. if searchResult.Hits.TotalHits != 1 {
  59. t.Errorf("expected SearchResult.Hits.TotalHits = %d; got %d", 1, searchResult.Hits.TotalHits)
  60. }
  61. if len(searchResult.Hits.Hits) != 1 {
  62. t.Errorf("expected len(SearchResult.Hits.Hits) = %d; got %d", 1, len(searchResult.Hits.Hits))
  63. }
  64. for _, hit := range searchResult.Hits.Hits {
  65. if hit.Index != testIndexName {
  66. t.Errorf("expected SearchResult.Hits.Hit.Index = %q; got %q", testIndexName, hit.Index)
  67. }
  68. item := make(map[string]interface{})
  69. err := json.Unmarshal(*hit.Source, &item)
  70. if err != nil {
  71. t.Fatal(err)
  72. }
  73. }
  74. }