search_queries_terms_test.go 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  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. "encoding/json"
  7. "testing"
  8. )
  9. func TestTermsQuery(t *testing.T) {
  10. q := NewTermsQuery("user", "ki")
  11. src, err := q.Source()
  12. if err != nil {
  13. t.Fatal(err)
  14. }
  15. data, err := json.Marshal(src)
  16. if err != nil {
  17. t.Fatalf("marshaling to JSON failed: %v", err)
  18. }
  19. got := string(data)
  20. expected := `{"terms":{"user":["ki"]}}`
  21. if got != expected {
  22. t.Errorf("expected\n%s\n,got:\n%s", expected, got)
  23. }
  24. }
  25. func TestTermsQueryWithEmptyArray(t *testing.T) {
  26. included := make([]interface{}, 0)
  27. q := NewTermsQuery("tags", included...)
  28. src, err := q.Source()
  29. if err != nil {
  30. t.Fatal(err)
  31. }
  32. data, err := json.Marshal(src)
  33. if err != nil {
  34. t.Fatalf("marshaling to JSON failed: %v", err)
  35. }
  36. got := string(data)
  37. expected := `{"terms":{"tags":[]}}`
  38. if got != expected {
  39. t.Errorf("expected\n%s\n,got:\n%s", expected, got)
  40. }
  41. }
  42. func TestTermsQueryWithTermsLookup(t *testing.T) {
  43. q := NewTermsQuery("user").
  44. TermsLookup(NewTermsLookup().Index("users").Type("user").Id("2").Path("followers"))
  45. src, err := q.Source()
  46. if err != nil {
  47. t.Fatal(err)
  48. }
  49. data, err := json.Marshal(src)
  50. if err != nil {
  51. t.Fatalf("marshaling to JSON failed: %v", err)
  52. }
  53. got := string(data)
  54. expected := `{"terms":{"user":{"id":"2","index":"users","path":"followers","type":"user"}}}`
  55. if got != expected {
  56. t.Errorf("expected\n%s\n,got:\n%s", expected, got)
  57. }
  58. }
  59. func TestTermQuerysWithOptions(t *testing.T) {
  60. q := NewTermsQuery("user", "ki", "ko")
  61. q = q.Boost(2.79)
  62. q = q.QueryName("my_tq")
  63. src, err := q.Source()
  64. if err != nil {
  65. t.Fatal(err)
  66. }
  67. data, err := json.Marshal(src)
  68. if err != nil {
  69. t.Fatalf("marshaling to JSON failed: %v", err)
  70. }
  71. got := string(data)
  72. expected := `{"terms":{"_name":"my_tq","boost":2.79,"user":["ki","ko"]}}`
  73. if got != expected {
  74. t.Errorf("expected\n%s\n,got:\n%s", expected, got)
  75. }
  76. }