Test
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

search_queries_terms_set_test.go 2.2KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  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. "testing"
  9. )
  10. func TestTermsSetQueryWithField(t *testing.T) {
  11. q := NewTermsSetQuery("codes", "abc", "def", "ghi").MinimumShouldMatchField("required_matches")
  12. src, err := q.Source()
  13. if err != nil {
  14. t.Fatal(err)
  15. }
  16. data, err := json.Marshal(src)
  17. if err != nil {
  18. t.Fatalf("marshaling to JSON failed: %v", err)
  19. }
  20. got := string(data)
  21. expected := `{"terms_set":{"codes":{"minimum_should_match_field":"required_matches","terms":["abc","def","ghi"]}}}`
  22. if got != expected {
  23. t.Errorf("expected\n%s\n,got:\n%s", expected, got)
  24. }
  25. }
  26. func TestTermsSetQueryWithScript(t *testing.T) {
  27. q := NewTermsSetQuery("codes", "abc", "def", "ghi").
  28. MinimumShouldMatchScript(
  29. NewScript(`Math.min(params.num_terms, doc['required_matches'].value)`),
  30. )
  31. src, err := q.Source()
  32. if err != nil {
  33. t.Fatal(err)
  34. }
  35. data, err := json.Marshal(src)
  36. if err != nil {
  37. t.Fatalf("marshaling to JSON failed: %v", err)
  38. }
  39. got := string(data)
  40. expected := `{"terms_set":{"codes":{"minimum_should_match_script":{"source":"Math.min(params.num_terms, doc['required_matches'].value)"},"terms":["abc","def","ghi"]}}}`
  41. if got != expected {
  42. t.Errorf("expected\n%s\n,got:\n%s", expected, got)
  43. }
  44. }
  45. func TestSearchTermsSetQuery(t *testing.T) {
  46. //client := setupTestClientAndCreateIndexAndAddDocs(t, SetTraceLog(log.New(os.Stdout, "", log.LstdFlags)))
  47. client := setupTestClientAndCreateIndexAndAddDocs(t)
  48. // Match all should return all documents
  49. searchResult, err := client.Search().
  50. Index(testIndexName).
  51. Query(
  52. NewTermsSetQuery("user", "olivere", "sandrae").
  53. MinimumShouldMatchField("retweets"),
  54. ).
  55. Pretty(true).
  56. Do(context.TODO())
  57. if err != nil {
  58. t.Fatal(err)
  59. }
  60. if searchResult.Hits == nil {
  61. t.Errorf("expected SearchResult.Hits != nil; got nil")
  62. }
  63. if got, want := searchResult.Hits.TotalHits, int64(3); got != want {
  64. t.Errorf("expected SearchResult.Hits.TotalHits = %d; got %d", want, got)
  65. }
  66. if got, want := len(searchResult.Hits.Hits), 3; got != want {
  67. t.Errorf("expected len(SearchResult.Hits.Hits) = %d; got %d", want, got)
  68. }
  69. }