search.go 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507
  1. // Copyright 2012-2015 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. "fmt"
  8. "net/url"
  9. "reflect"
  10. "strings"
  11. "github.com/olivere/elastic/uritemplates"
  12. )
  13. // Search for documents in Elasticsearch.
  14. type SearchService struct {
  15. client *Client
  16. searchSource *SearchSource
  17. source interface{}
  18. pretty bool
  19. searchType string
  20. indices []string
  21. queryHint string
  22. routing string
  23. preference string
  24. types []string
  25. }
  26. // NewSearchService creates a new service for searching in Elasticsearch.
  27. // You typically do not create the service yourself manually, but access
  28. // it via client.Search().
  29. func NewSearchService(client *Client) *SearchService {
  30. builder := &SearchService{
  31. client: client,
  32. searchSource: NewSearchSource(),
  33. }
  34. return builder
  35. }
  36. // SearchSource sets the search source builder to use with this service.
  37. func (s *SearchService) SearchSource(searchSource *SearchSource) *SearchService {
  38. s.searchSource = searchSource
  39. if s.searchSource == nil {
  40. s.searchSource = NewSearchSource()
  41. }
  42. return s
  43. }
  44. // Source allows the user to set the request body manually without using
  45. // any of the structs and interfaces in Elastic.
  46. func (s *SearchService) Source(source interface{}) *SearchService {
  47. s.source = source
  48. return s
  49. }
  50. // Index sets the name of the index to use for search.
  51. func (s *SearchService) Index(index string) *SearchService {
  52. if s.indices == nil {
  53. s.indices = make([]string, 0)
  54. }
  55. s.indices = append(s.indices, index)
  56. return s
  57. }
  58. // Indices sets the names of the indices to use for search.
  59. func (s *SearchService) Indices(indices ...string) *SearchService {
  60. if s.indices == nil {
  61. s.indices = make([]string, 0)
  62. }
  63. s.indices = append(s.indices, indices...)
  64. return s
  65. }
  66. // Type restricts the search for the given type.
  67. func (s *SearchService) Type(typ string) *SearchService {
  68. if s.types == nil {
  69. s.types = []string{typ}
  70. } else {
  71. s.types = append(s.types, typ)
  72. }
  73. return s
  74. }
  75. // Types allows to restrict the search to a list of types.
  76. func (s *SearchService) Types(types ...string) *SearchService {
  77. if s.types == nil {
  78. s.types = make([]string, len(types))
  79. }
  80. s.types = append(s.types, types...)
  81. return s
  82. }
  83. // Pretty enables the caller to indent the JSON output.
  84. func (s *SearchService) Pretty(pretty bool) *SearchService {
  85. s.pretty = pretty
  86. return s
  87. }
  88. // Timeout sets the timeout to use, e.g. "1s" or "1000ms".
  89. func (s *SearchService) Timeout(timeout string) *SearchService {
  90. s.searchSource = s.searchSource.Timeout(timeout)
  91. return s
  92. }
  93. // TimeoutInMillis sets the timeout in milliseconds.
  94. func (s *SearchService) TimeoutInMillis(timeoutInMillis int) *SearchService {
  95. s.searchSource = s.searchSource.TimeoutInMillis(timeoutInMillis)
  96. return s
  97. }
  98. // SearchType sets the search operation type. Valid values are:
  99. // "query_then_fetch", "query_and_fetch", "dfs_query_then_fetch",
  100. // "dfs_query_and_fetch", "count", "scan".
  101. // See http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/search-request-search-type.html#search-request-search-type
  102. // for details.
  103. func (s *SearchService) SearchType(searchType string) *SearchService {
  104. s.searchType = searchType
  105. return s
  106. }
  107. // Routing allows for (a comma-separated) list of specific routing values.
  108. func (s *SearchService) Routing(routing string) *SearchService {
  109. s.routing = routing
  110. return s
  111. }
  112. // Preference specifies the node or shard the operation should be
  113. // performed on (default: "random").
  114. func (s *SearchService) Preference(preference string) *SearchService {
  115. s.preference = preference
  116. return s
  117. }
  118. func (s *SearchService) QueryHint(queryHint string) *SearchService {
  119. s.queryHint = queryHint
  120. return s
  121. }
  122. // Query sets the query to perform, e.g. MatchAllQuery.
  123. func (s *SearchService) Query(query Query) *SearchService {
  124. s.searchSource = s.searchSource.Query(query)
  125. return s
  126. }
  127. // PostFilter is executed as the last filter. It only affects the
  128. // search hits but not facets. See
  129. // http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/search-request-post-filter.html
  130. // for details.
  131. func (s *SearchService) PostFilter(postFilter Filter) *SearchService {
  132. s.searchSource = s.searchSource.PostFilter(postFilter)
  133. return s
  134. }
  135. // Highlight sets the highlighting. See
  136. // http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/search-request-highlighting.html
  137. // for details.
  138. func (s *SearchService) Highlight(highlight *Highlight) *SearchService {
  139. s.searchSource = s.searchSource.Highlight(highlight)
  140. return s
  141. }
  142. // GlobalSuggestText sets the global text for suggesters. See
  143. // http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/search-suggesters.html#global-suggest
  144. // for details.
  145. func (s *SearchService) GlobalSuggestText(globalText string) *SearchService {
  146. s.searchSource = s.searchSource.GlobalSuggestText(globalText)
  147. return s
  148. }
  149. // Suggester sets the suggester. See
  150. // http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/search-suggesters.html
  151. // for details.
  152. func (s *SearchService) Suggester(suggester Suggester) *SearchService {
  153. s.searchSource = s.searchSource.Suggester(suggester)
  154. return s
  155. }
  156. // Facet adds a facet to the search. See
  157. // http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/search-facets.html
  158. // to get an overview of Elasticsearch facets.
  159. func (s *SearchService) Facet(name string, facet Facet) *SearchService {
  160. s.searchSource = s.searchSource.Facet(name, facet)
  161. return s
  162. }
  163. // Aggregation adds an aggregation to the search. See
  164. // http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/search-aggregations.html
  165. // for an overview of aggregations in Elasticsearch.
  166. func (s *SearchService) Aggregation(name string, aggregation Aggregation) *SearchService {
  167. s.searchSource = s.searchSource.Aggregation(name, aggregation)
  168. return s
  169. }
  170. // MinScore excludes documents which have a score less than the minimum
  171. // specified here. See http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/search-request-min-score.html.
  172. func (s *SearchService) MinScore(minScore float64) *SearchService {
  173. s.searchSource = s.searchSource.MinScore(minScore)
  174. return s
  175. }
  176. // From defines the offset from the first result you want to fetch.
  177. // Use it in combination with Size to paginate through results.
  178. // See http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/search-request-from-size.html
  179. // for details.
  180. func (s *SearchService) From(from int) *SearchService {
  181. s.searchSource = s.searchSource.From(from)
  182. return s
  183. }
  184. // Size defines the maximum number of hits to be returned.
  185. // Use it in combination with From to paginate through results.
  186. // See http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/search-request-from-size.html
  187. // for details.
  188. func (s *SearchService) Size(size int) *SearchService {
  189. s.searchSource = s.searchSource.Size(size)
  190. return s
  191. }
  192. // Explain can be enabled to provide an explanation for each hit and how its
  193. // score was computed.
  194. // See http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/search-request-explain.html
  195. // for details.
  196. func (s *SearchService) Explain(explain bool) *SearchService {
  197. s.searchSource = s.searchSource.Explain(explain)
  198. return s
  199. }
  200. // Version can be set to true to return a version for each search hit.
  201. // See http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/search-request-version.html.
  202. func (s *SearchService) Version(version bool) *SearchService {
  203. s.searchSource = s.searchSource.Version(version)
  204. return s
  205. }
  206. // Sort the results by the given field, in the given order.
  207. // Use the alternative SortWithInfo to use a struct to define the sorting.
  208. // See http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/search-request-sort.html
  209. // for detailed documentation of sorting.
  210. func (s *SearchService) Sort(field string, ascending bool) *SearchService {
  211. s.searchSource = s.searchSource.Sort(field, ascending)
  212. return s
  213. }
  214. // SortWithInfo defines how to sort results.
  215. // Use the Sort func for a shortcut.
  216. // See http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/search-request-sort.html
  217. // for detailed documentation of sorting.
  218. func (s *SearchService) SortWithInfo(info SortInfo) *SearchService {
  219. s.searchSource = s.searchSource.SortWithInfo(info)
  220. return s
  221. }
  222. // SortBy defines how to sort results.
  223. // Use the Sort func for a shortcut.
  224. // See http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/search-request-sort.html
  225. // for detailed documentation of sorting.
  226. func (s *SearchService) SortBy(sorter ...Sorter) *SearchService {
  227. s.searchSource = s.searchSource.SortBy(sorter...)
  228. return s
  229. }
  230. // Fields tells Elasticsearch to only load specific fields from a search hit.
  231. // See http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/search-request-fields.html.
  232. func (s *SearchService) Fields(fields ...string) *SearchService {
  233. s.searchSource = s.searchSource.Fields(fields...)
  234. return s
  235. }
  236. // Do executes the search and returns a SearchResult.
  237. func (s *SearchService) Do() (*SearchResult, error) {
  238. // Build url
  239. path := "/"
  240. // Indices part
  241. indexPart := make([]string, 0)
  242. for _, index := range s.indices {
  243. index, err := uritemplates.Expand("{index}", map[string]string{
  244. "index": index,
  245. })
  246. if err != nil {
  247. return nil, err
  248. }
  249. indexPart = append(indexPart, index)
  250. }
  251. path += strings.Join(indexPart, ",")
  252. // Types part
  253. if len(s.types) > 0 {
  254. typesPart := make([]string, 0)
  255. for _, typ := range s.types {
  256. typ, err := uritemplates.Expand("{type}", map[string]string{
  257. "type": typ,
  258. })
  259. if err != nil {
  260. return nil, err
  261. }
  262. typesPart = append(typesPart, typ)
  263. }
  264. path += "/"
  265. path += strings.Join(typesPart, ",")
  266. }
  267. // Search
  268. path += "/_search"
  269. // Parameters
  270. params := make(url.Values)
  271. if s.pretty {
  272. params.Set("pretty", fmt.Sprintf("%v", s.pretty))
  273. }
  274. if s.searchType != "" {
  275. params.Set("search_type", s.searchType)
  276. }
  277. // Perform request
  278. var body interface{}
  279. if s.source != nil {
  280. body = s.source
  281. } else {
  282. body = s.searchSource.Source()
  283. }
  284. res, err := s.client.PerformRequest("POST", path, params, body)
  285. if err != nil {
  286. return nil, err
  287. }
  288. // Return search results
  289. ret := new(SearchResult)
  290. if err := json.Unmarshal(res.Body, ret); err != nil {
  291. return nil, err
  292. }
  293. return ret, nil
  294. }
  295. // SearchResult is the result of a search in Elasticsearch.
  296. type SearchResult struct {
  297. TookInMillis int64 `json:"took"` // search time in milliseconds
  298. ScrollId string `json:"_scroll_id"` // only used with Scroll and Scan operations
  299. Hits *SearchHits `json:"hits"` // the actual search hits
  300. Suggest SearchSuggest `json:"suggest"` // results from suggesters
  301. Facets SearchFacets `json:"facets"` // results from facets
  302. Aggregations Aggregations `json:"aggregations"` // results from aggregations
  303. TimedOut bool `json:"timed_out"` // true if the search timed out
  304. Error string `json:"error,omitempty"` // used in MultiSearch only
  305. }
  306. // TotalHits is a convenience function to return the number of hits for
  307. // a search result.
  308. func (r *SearchResult) TotalHits() int64 {
  309. if r.Hits != nil {
  310. return r.Hits.TotalHits
  311. }
  312. return 0
  313. }
  314. // Each is a utility function to iterate over all hits. It saves you from
  315. // checking for nil values. Notice that Each will ignore errors in
  316. // serializing JSON.
  317. func (r *SearchResult) Each(typ reflect.Type) []interface{} {
  318. if r.Hits == nil || r.Hits.Hits == nil || len(r.Hits.Hits) == 0 {
  319. return nil
  320. }
  321. slice := make([]interface{}, 0)
  322. for _, hit := range r.Hits.Hits {
  323. v := reflect.New(typ).Elem()
  324. if err := json.Unmarshal(*hit.Source, v.Addr().Interface()); err == nil {
  325. slice = append(slice, v.Interface())
  326. }
  327. }
  328. return slice
  329. }
  330. // SearchHits specifies the list of search hits.
  331. type SearchHits struct {
  332. TotalHits int64 `json:"total"` // total number of hits found
  333. MaxScore *float64 `json:"max_score"` // maximum score of all hits
  334. Hits []*SearchHit `json:"hits"` // the actual hits returned
  335. }
  336. // SearchHit is a single hit.
  337. type SearchHit struct {
  338. Score *float64 `json:"_score"` // computed score
  339. Index string `json:"_index"` // index name
  340. Id string `json:"_id"` // external or internal
  341. Type string `json:"_type"` // type
  342. Version *int64 `json:"_version"` // version number, when Version is set to true in SearchService
  343. Sort []interface{} `json:"sort"` // sort information
  344. Highlight SearchHitHighlight `json:"highlight"` // highlighter information
  345. Source *json.RawMessage `json:"_source"` // stored document source
  346. Fields map[string]interface{} `json:"fields"` // returned fields
  347. Explanation *SearchExplanation `json:"_explanation"` // explains how the score was computed
  348. // Shard
  349. // HighlightFields
  350. // SortValues
  351. // MatchedFilters
  352. }
  353. // SearchExplanation explains how the score for a hit was computed.
  354. // See http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/search-request-explain.html.
  355. type SearchExplanation struct {
  356. Value float64 `json:"value"` // e.g. 1.0
  357. Description string `json:"description"` // e.g. "boost" or "ConstantScore(*:*), product of:"
  358. Details []SearchExplanation `json:"details,omitempty"` // recursive details
  359. }
  360. // Suggest
  361. // SearchSuggest is a map of suggestions.
  362. // See http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/search-suggesters.html.
  363. type SearchSuggest map[string][]SearchSuggestion
  364. // SearchSuggestion is a single search suggestion.
  365. // See http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/search-suggesters.html.
  366. type SearchSuggestion struct {
  367. Text string `json:"text"`
  368. Offset int `json:"offset"`
  369. Length int `json:"length"`
  370. Options []SearchSuggestionOption `json:"options"`
  371. }
  372. // SearchSuggestionOption is an option of a SearchSuggestion.
  373. // See http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/search-suggesters.html.
  374. type SearchSuggestionOption struct {
  375. Text string `json:"text"`
  376. Score float32 `json:"score"`
  377. Freq int `json:"freq"`
  378. Payload interface{} `json:"payload"`
  379. }
  380. // Facets
  381. // SearchFacets is a map of facets.
  382. // See http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/search-facets.html.
  383. type SearchFacets map[string]*SearchFacet
  384. // SearchFacet is a single facet.
  385. // See http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/search-facets.html.
  386. type SearchFacet struct {
  387. Type string `json:"_type"`
  388. Missing int `json:"missing"`
  389. Total int `json:"total"`
  390. Other int `json:"other"`
  391. Terms []searchFacetTerm `json:"terms"`
  392. Ranges []searchFacetRange `json:"ranges"`
  393. Entries []searchFacetEntry `json:"entries"`
  394. }
  395. // searchFacetTerm is the result of a terms facet.
  396. // See http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/search-facets-terms-facet.html.
  397. type searchFacetTerm struct {
  398. Term string `json:"term"`
  399. Count int `json:"count"`
  400. }
  401. // searchFacetRange is the result of a range facet.
  402. // See http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/search-facets-range-facet.html.
  403. type searchFacetRange struct {
  404. From *float64 `json:"from"`
  405. FromStr *string `json:"from_str"`
  406. To *float64 `json:"to"`
  407. ToStr *string `json:"to_str"`
  408. Count int `json:"count"`
  409. Min *float64 `json:"min"`
  410. Max *float64 `json:"max"`
  411. TotalCount int `json:"total_count"`
  412. Total *float64 `json:"total"`
  413. Mean *float64 `json:"mean"`
  414. }
  415. // searchFacetEntry is a general facet entry.
  416. // See http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/search-facets.html
  417. type searchFacetEntry struct {
  418. // Key for this facet, e.g. in histograms
  419. Key interface{} `json:"key"`
  420. // Date histograms contain the number of milliseconds as date:
  421. // If e.Time = 1293840000000, then: Time.at(1293840000000/1000) => 2011-01-01
  422. Time int64 `json:"time"`
  423. // Number of hits for this facet
  424. Count int `json:"count"`
  425. // Min is either a string like "Infinity" or a float64.
  426. // This is returned with some DateHistogram facets.
  427. Min interface{} `json:"min,omitempty"`
  428. // Max is either a string like "-Infinity" or a float64
  429. // This is returned with some DateHistogram facets.
  430. Max interface{} `json:"max,omitempty"`
  431. // Total is the sum of all entries on the recorded Time
  432. // This is returned with some DateHistogram facets.
  433. Total float64 `json:"total,omitempty"`
  434. // TotalCount is the number of entries for Total
  435. // This is returned with some DateHistogram facets.
  436. TotalCount int `json:"total_count,omitempty"`
  437. // Mean is the mean value
  438. // This is returned with some DateHistogram facets.
  439. Mean float64 `json:"mean,omitempty"`
  440. }
  441. // Aggregations (see search_aggs.go)
  442. // Highlighting
  443. // SearchHitHighlight is the highlight information of a search hit.
  444. // See http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/search-request-highlighting.html
  445. // for a general discussion of highlighting.
  446. type SearchHitHighlight map[string][]string