search_queries_wildcard_test.go 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  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_test
  5. import (
  6. "context"
  7. "encoding/json"
  8. "testing"
  9. "gopkg.in/olivere/elastic.v5"
  10. )
  11. func ExampleWildcardQuery() {
  12. // Get a client to the local Elasticsearch instance.
  13. client, err := elastic.NewClient()
  14. if err != nil {
  15. // Handle error
  16. panic(err)
  17. }
  18. // Define wildcard query
  19. q := elastic.NewWildcardQuery("user", "oli*er?").Boost(1.2)
  20. searchResult, err := client.Search().
  21. Index("twitter"). // search in index "twitter"
  22. Query(q). // use wildcard query defined above
  23. Do(context.TODO()) // execute
  24. if err != nil {
  25. // Handle error
  26. panic(err)
  27. }
  28. _ = searchResult
  29. }
  30. func TestWildcardQuery(t *testing.T) {
  31. q := elastic.NewWildcardQuery("user", "ki*y??")
  32. src, err := q.Source()
  33. if err != nil {
  34. t.Fatal(err)
  35. }
  36. data, err := json.Marshal(src)
  37. if err != nil {
  38. t.Fatalf("marshaling to JSON failed: %v", err)
  39. }
  40. got := string(data)
  41. expected := `{"wildcard":{"user":{"wildcard":"ki*y??"}}}`
  42. if got != expected {
  43. t.Errorf("expected\n%s\n,got:\n%s", expected, got)
  44. }
  45. }
  46. func TestWildcardQueryWithBoost(t *testing.T) {
  47. q := elastic.NewWildcardQuery("user", "ki*y??").Boost(1.2)
  48. src, err := q.Source()
  49. if err != nil {
  50. t.Fatal(err)
  51. }
  52. data, err := json.Marshal(src)
  53. if err != nil {
  54. t.Fatalf("marshaling to JSON failed: %v", err)
  55. }
  56. got := string(data)
  57. expected := `{"wildcard":{"user":{"boost":1.2,"wildcard":"ki*y??"}}}`
  58. if got != expected {
  59. t.Errorf("expected\n%s\n,got:\n%s", expected, got)
  60. }
  61. }