Upversion artifacts to 1.8.0-SNAPSHOT
[aai/search-data-service.git] / SEARCH.md
1 # Search Requests\r
2 \r
3 ## Overview\r
4 Ultimately, the point of storing documents in a document store is to be able to access the data embodied in those documents in a variety of interesting ways.  To put it another way, we want to be able to ask interesting questions of the data that has been persisted, not just get back a document that we put in.\r
5 \r
6 We do this by submitting _Search Requests_ to the _Search Service_.\r
7 \r
8 Conceptually, the structure of a _Search Request_ can be visualized as a pipeline consisting of three phases of operations that are applied to our document set in order to produce a query result set:\r
9 \r
10     +---------------------+\r
11     | ENTIRE DOCUMENT SET | ----------------------------- We begin with the entire set of documents in our index.\r
12     +---------------------+\r
13                |\r
14                V\r
15         \-------------/          \r
16          \ Filter(s) / ---------------------------------- We optionally apply a set of filter criteria to the document \r
17           -----------                                     set, with the intent of reducing the overall set of documents \r
18                |                                          that we will be applying our query against (filtering is cheaper \r
19                |                                          than running the full queries)\r
20                V                   \r
21       +-----------------+        \r
22       | DOCUMENT SUBSET | ------------------------------- Our filter stage produces a (hopefully) smaller subset of documents \r
23       +-----------------+                                 than we started with.\r
24                |\r
25                V\r
26          \-----------/      \r
27           \ Queries / ----------------------------------- Now we execute our queries against the filtered document subset.\r
28            --------- \r
29                |\r
30                V\r
31      +------------------+          \r
32      | QUERY RESULT SET | ------------------------------- This produces a scored set of results. \r
33      +------------------+            \r
34                |                     \r
35                V                                \r
36       \----------------/             \r
37        \ Aggregations / --------------------------------- Optionally we may apply a set of aggregations against the query               \r
38         --------------                                    result set.\r
39                |                     \r
40                V                     \r
41     +---------------------+          \r
42     | AGGREGATION BUCKETS | ----------------------------- This produces a set of aggregation buckets based on the query\r
43     +---------------------+                               result set.\r
44 \r
45 \r
46 \r
47 ### Filters\r
48 _Filters_ are intended to answer the following question about the documents that they are applied to:  _Does this document match the specified criteria?_\r
49 \r
50 In other words, filter queries produce **yes/no** results.  A given document either **IS** or **IS NOT** in the set of documents that we want.  This can also be described as a _non-scored_ search and is typically a cheaper operation than performing a _scored_ search (more on those below).  This is why we often want to pre-filter our document set before applying more expensive query operations.\r
51 \r
52 ### Queries\r
53 _Queries_ are intended to answer the following question about the documents that they are applied to: _How well does this document match the specified criteria?_ \r
54 \r
55 In other words, the criteria which we include in our _Query_ is not intended to produce a set of _yes/no_ results, but a _scored_ result set which includes the set of documents that meet some combination of the criteria which we supply and includes a _score_ indicating _how well_ a particular document meets the overall requirement set.  The more criteria that a particular document meets, the higher its score.\r
56 \r
57 ### Aggregations\r
58 _Aggregations_ are intended to answer questions that summarize and analyze an overall data set (typically a _Query_ result set).\r
59 \r
60 _Aggregations_ produce result sets that group the data set into buckets, based on the _Aggregation_ criteria, and allow questions such as the following to be asked:\r
61 \r
62 * Of all of the people in my result set, how many are taller than 5' 10"?\r
63 * How many different server vendors have hardware installed in my network?\r
64 * What proportion of employees serviced by our IT department use Macs?  What proportion use Windows?\r
65 \r
66 ## Syntax\r
67 \r
68 ### The Filter Stanza\r
69 \r
70 If you intend for your _Search Request_ to include a _Filter_ stage, then you must define the _filter queries_ that you wish to be applied in the _Filter Stanza_ of your _Search Request_.  The following pseudo-json illustrates the structure of the _Filter Stanza_:\r
71 \r
72     {\r
73         "filter": {\r
74             "all": [ {filter-query}, {filter-query}, ... {filter-query}],\r
75             "any": [ {filter-query}, {filter-query}, ... {filter-query}]\r
76         }\r
77     }\r
78 \r
79 As we can see, our _Filter Stanza_ consists of two optional groupings of _query_ statements: _any_ and _all_.  These groupings will produce the following behaviours:\r
80 \r
81 * _all_ - _Documents_ must match ALL of the _queries_ in this grouping in order to be included in the result set.\r
82 * _any_ - _Documents_ must match a minimum of ONE of the _queries_ in this grouping in order to be included in the result set.\r
83 \r
84 The _filter-queries_ themselves are syntactically identical to the _Queries_ which we will define below, the only difference being that, because they are declared within the _Filter Stanza_ they will be applied as _unscored_ queries.\r
85 \r
86 ### The Query Stanza\r
87 \r
88 The _Query Stanza_ is where we define _query statements_ which are intended to produce _scored results_, as opposed to _queries_ which are intended for filtering purposes.\r
89 \r
90 The _Query Stanza_ is expressed as a list of _query statements_, each of which is prefixed with a directive indicating how strongly the _query_ in question is to be applied.\r
91 \r
92 _Queries_ prefixed with the "must" directive, represent queries which all documents must satisfy to be included in the result set, whereas, _queries_ prefixed with the "may" directive represent queries which are not required for a document to be included in the result set, although they will score higher if they do.\r
93 \r
94 The following pseudo-json illustrates the structure of the _Query Stanza_:\r
95  \r
96     {\r
97         "queries": [\r
98             { "must": { <query> } },\r
99             { "must": { <query> } },\r
100                  .\r
101                  .\r
102             { "must": { <query> } },\r
103             { "may" : { <query> } },\r
104                  .\r
105                  .\r
106             { "may" : { <query> } }\r
107         ]\r
108     }\r
109 \r
110 **Nested Fields** - If the document to be queried contains nested fields, then these may be referenced by providing the fully qualified field name using dotted notation.  Example: _myFieldName.mySubFieldName_\r
111 \r
112 ** Result-Set Restrictions** - In some cases, where the number of hits for a given set of queries is expected to be large, the client may want to restrict the size of the result set that is returned, as well as manipulate which subset of results it gets back.  This can be accomplished with the following optional fields in the Search Statement:\r
113 * results-start - Index into the result set to the first document to be returned.\r
114 * results-size - The maximum number of documents to be returned in the result set.\r
115 \r
116 Both of these fields are optional - leaving them out implies that the entire result set should be returned to the client.\r
117 \r
118 **IMPORTANT - Note that although the these two fields may be used by the client to get back query results a chunk at a time by resending the same query repeatedly and specifying a different 'results-start' value each time, be aware that this is NOT a transactional operation.  There is no guarantee that changes to the underlying data may not occur in between query calls.  This is NOT intended to be the equivalent of a mechanism such as the 'Scroll API' provided by ElasticSearch or a cursor in a traditional data base.**\r
119 \r
120 We will discuss the specific query types supported below, and then provide some concrete examples.\r
121 \r
122 **Term Query**\r
123 \r
124 A _Term_ query attempts to match the literal value of a field, with no advanced parsing or analysis of the query string.\r
125 \r
126 There are two operations supported by the _Term_ query type:\r
127 * match - The contents of the specified field must match the supplied value.\r
128 * not-match - The contents of the specified field must NOT match the supplied value.\r
129 \r
130 _Example - Simple Match_\r
131 \r
132     {\r
133         "match": { "FirstName": "Bob" }\r
134     }\r
135     \r
136 _Example - Simple Not-Match_\r
137 \r
138     {\r
139         "not-match": { "LastName": "Smith" }\r
140     }\r
141     \r
142 Note that the term match is applied against the tokenized field contents.\r
143 \r
144 For example, if a field containing the contents: "_the quick brown fox_" was analyzed with a white space tokenizer (this occurs on document creation or update), the following inverted indexes would be created for the field at the time of document insertion:\r
145 \r
146     the\r
147     quick\r
148     brown\r
149     fox\r
150 \r
151 Meaning that the following term queries would all produce a match for our document:\r
152 \r
153          {"must": {"match": { "my-field-name": "the"}}}\r
154          {"must": {"match": { "my-field-name": "quick"}}}\r
155          {"must": {"match": { "my-field-name": "brown"}}}\r
156          {"must": {"match": { "my-field-name": "fox"}}}\r
157 \r
158          \r
159 **Multi Field Term Query**\r
160 \r
161 A variant of the _Term_ query described above is the  _Multi Field Term Query_, which, as the name suggests, allows for a _Term_ query to be applied across multiple fields.  The syntax is the same as for a single field term query except that the fields are supplied as a space-delimited list, as in the example below:\r
162 \r
163     {"must": {"match": {"field": "field1 field2 field3", "value": "blah"}}}\r
164 \r
165 The above query would produce a hit for any documents containing the value "blah" in any of "field1", "field2", or "field3".\r
166  \r
167 Note that it is also valid to supply multiple values in the same manner, by supplying a space-delimited list in the "value" field.\r
168 \r
169 The default behaviour in this case is to produce a hit only if there is at least one occurrence of EVERY supplied value in any of the specified fields.\r
170 \r
171 For example, the following query:\r
172 \r
173     {"must": {"match": {"field": "first_name last_name", "value": "Smith Will"}}}\r
174   \r
175 Produces a match for document {"first_name": "Will", "last_name": "Smith"} but not {"first_name": "Will", "last_name": "Shakespeare"}\r
176  \r
177 This default behaviour can be overriden by explicitly specifying a boolean operator for the query.  Valid operators are as follows:\r
178 * and - At least one occurrence of every value must be present in one of the specified fields to produce a hit. (This is the default behaviour if no operation is specified).\r
179 * or - An occurrence of any of the specified values in any of the specified fields will produce a hit.\r
180  \r
181 Restating the previous example with the operator explicitly specified illustrates the difference between the two operations:\r
182 \r
183 _Example - Multi field term query with AND operator explicitly set:_\r
184 \r
185     {"must": {"match": {"field": "first_name last_name", "value": "Smith Will", "operator": "and"}}}\r
186   \r
187 Produces a match for document {"first_name": "Will", "last_name": "Smith"} but not {"first_name": "Will", "last_name": "Shakespeare"} -- Exactly as in our previous example since this is the default behaviour.\r
188   \r
189   \r
190 _Example - Multi field term query with OR operator explicitly set:_\r
191 \r
192     {"must": {"match": {"field": "first_name last_name", "value": "Smith Will", "operator": "or"}}}\r
193   \r
194 Produces a match for both documents {"first_name": "Will", "last_name": "Smith"} and {"first_name": "Will", "last_name": "Shakespeare"}\r
195 \r
196 **Parsed Query**\r
197 \r
198 Parsed queries apply a query parser to the supplied query string in order to determine the exact query to apply to the specified field.\r
199 The query string is parsed into a series of terms and operators, as described below:\r
200 \r
201 _Terms_\r
202 \r
203 Terms may be any of the following:\r
204 * single words\r
205 * exact phrases, as denoted by enclosing the phrase in open and close quotations.  Example: "this is my exact phrase"\r
206 * regular expressions, as denoted by wrapping the expressing in forward slash ( / ) character.  Example: /joh?n(ath[oa]n)/\r
207 \r
208 Note that a series of terms with no explicit operators will be interpreted as a set of optional values.  For example:\r
209 \r
210     quick brown fox  would match fields which contain quick OR brown OR fox.\r
211 \r
212 _Operators_\r
213 \r
214 Operators provide for more complexity in terms of the behaviour described by the query string.  The supported operators are as follows:\r
215 \r
216 | Operator | Description                                                              | Example        |\r
217 | -------- | ------------------------------------------------------------------------ | -------------- |\r
218 | +            | The term to the right of the operator must be present.                   | +quick         |\r
219 | -            | The term to the right of the operator must not be present                | -brown         |\r
220 | AND      | Both the terms to the left and right of the operator must be present     | brown AND fox  |\r
221 | OR       | Either the term to the left or right of the operator must be present     | quick OR brown |\r
222 | NOT      | The term to the right of the operator must not be present (similar to -) | NOT fox        |\r
223  \r
224 The following pseudo-json illustrates the structure of a parsed query:\r
225 \r
226     "parsed-query": {\r
227         "field": "fieldname",      // If this field is not present, then apply the query to ALL fields\r
228         "query-string": "string"\r
229     }\r
230 \r
231 \r
232 **Range Query**\r
233 \r
234 _Range_ queries match fields whose term value falls within the specified numeric or date range.\r
235 \r
236 For fields containing date types, the default format for that field (as provided in the document schema when the index was created) will be used, unless the client overrides that with their own format string.\r
237 \r
238 A _Range_ query includes one or a combination of operations representing the upper and lower bounds of the range.  The following describes the supported bounds operations:\r
239 \r
240 | Operation | Description            |\r
241 | --------- | ---------------------- |\r
242 | gt        | Greater than           |\r
243 | gte       | Greater than or equals |\r
244 | lt        | Less than              |\r
245 | lte       | Less than or equals    |\r
246  \r
247 The following pseudo-json describes the structure of a ranged query.\r
248 \r
249     "range": {\r
250         "field": "fieldname",\r
251         "<<operation>>": numeric-or-date-value,     // where <<operation>> is one of the operations from the table above.\r
252               .\r
253               .\r
254         "<<operation>>": numeric-or-date-value,     // where <<operation>> is one of the operations from the table above.\r
255         "format": "format-string"                   // For date ranges, this allows the client to override the format defined \r
256                                                     // for the field in the document schema.\r
257         "time-zone": "+1:00"                        // For date ranges, this allows the client to specify a time zone parameter \r
258                                                     // to be applied to the lower and upper bounds of the query.\r
259     }\r
260 \r
261 ### The Aggregations Stanza\r
262 \r
263 **Group By Aggregation**\r
264 \r
265 _Group By_ aggregations create buckets based on the values in a specific field.  These are expressed in the following manner:\r
266 \r
267 _Example - Group by last name, excluding any buckets with less than 2 entries._\r
268 \r
269     {\r
270         "name": "GroupByLastName",\r
271         "aggregation" : {\r
272             "group-by": {\r
273                 "field": "LastName",\r
274                 "min-threshold": 2\r
275             }\r
276         }\r
277     }\r
278 \r
279 \r
280 **Date Range Aggregation**\r
281 \r
282 _Date Range_ aggregations produce counts where date type fields fall in or out of a particular range.\r
283 \r
284 _Example - Return counts of the number of people born before Jan 1, 1972 and the number of people born after Jan 1, 1972_\r
285 \r
286     {\r
287         "name": "AggregateByBirthdate",\r
288         "aggregation": {\r
289             "date-range": {\r
290                 "field": "BirthDate",\r
291                 "from": "01-01-1972 00:00:00",\r
292                 "to": "01-01-1972 00:00:00"\r
293             }\r
294         }\r
295     }\r
296 \r
297 ### Putting It All Together\r
298 \r
299 The following examples illustrate how to construct a complete search statement, putting all of the previous building blocks together, starting with the simplest possible search statement, and building toward more complicated request that combine, filters, scored queries, and aggregations.\r
300 \r
301 _Example - Simple search statement with no filtering or aggregations_\r
302 \r
303 Search Statement:\r
304 \r
305     {\r
306         "queries": [\r
307             {"must": {"match": {"field": "LastName", "value": "Smith"}}}   \r
308         ]\r
309     }\r
310 \r
311 Response Body:\r
312 \r
313     {\r
314         "searchResult": {\r
315             "totalHits": 3,\r
316             "hits": [\r
317                 {\r
318                      "score": 0.8,\r
319                      "document": {\r
320                          "url": "/indexes/people/documents/8",\r
321                          "etag": "3",\r
322                          "content": {\r
323                              "FirstName": "Will",\r
324                              "LastName": "Smith"\r
325                          }\r
326                      }\r
327                  },\r
328                  {\r
329                      "score": 0.8,\r
330                      "document": {\r
331                          "url": "/indexes/people/documents/2",\r
332                          "etag": "1",\r
333                          "content": {\r
334                              "FirstName": "Bob",\r
335                              "LastName": "Smith"\r
336                          }\r
337                      }\r
338                  },\r
339                  {\r
340                      "score": 0.8,\r
341                      "document": {\r
342                          "url": "/indexes/people/documents/10",\r
343                          "etag": "7",\r
344                          "content": {\r
345                              "FirstName": "Alan",\r
346                              "LastName": "Smith"\r
347                          }\r
348                      }\r
349                  }\r
350             ]\r
351         }\r
352     }\r
353 \r
354 _Example - Simple search statement with multiple term queries, with no filtering or aggregations_\r
355 \r
356 Search Statement:\r
357 \r
358     {\r
359         "queries": [\r
360             {"must": {"match": {"field": "LastName", "value": "Smith"}}},\r
361             {"may": {"match": {"field": "FirstName", "value", "Bob"}}},\r
362             {"must": {"not-match": {"field": "FirstName", "value", "Alan"}}}\r
363         ]\r
364     }\r
365 \r
366 Response Body:\r
367 \r
368     {\r
369         "searchResult": {\r
370             "totalHits": 2,\r
371             "hits": [\r
372                 {\r
373                      "score": 0.8,\r
374                      "document": {\r
375                          "url": "/indexes/people/documents/8",\r
376                          "etag": "3",\r
377                          "content": {\r
378                              "FirstName": "Bob",\r
379                              "LastName": "Smith"\r
380                          }\r
381                      }\r
382                  },\r
383                  {\r
384                      "score": 0.5,\r
385                      "document": {\r
386                          "url": "/indexes/people/documents/2",\r
387                          "etag": "1",\r
388                          "content": {\r
389                              "FirstName": "Will",\r
390                              "LastName": "Smith"\r
391                          }\r
392                      }\r
393                  }\r
394             ]\r
395         }\r
396     }\r
397     \r
398 _Example - Simple search statement with a filter stanza_\r
399 \r
400 Search Statement:\r
401 \r
402     {\r
403         "filter": {\r
404             "all": {\r
405                 { "must": {"not-match": {"field": "FirstName", "value", "Bob"}}}\r
406             }\r
407         },\r
408         \r
409         "queries": [\r
410             {"must": {"match": {"field": "LastName", "value": "Smith"}}},\r
411         ]\r
412     }\r
413 \r
414 Response Body:\r
415 \r
416     {\r
417         "searchResult": {\r
418             "totalHits": 2,\r
419             "hits": [\r
420                 {\r
421                      "score": 0.8,\r
422                      "document": {\r
423                          "url": "/indexes/people/documents/8",\r
424                          "etag": "3",\r
425                          "content": {\r
426                              "FirstName": "Will",\r
427                              "LastName": "Smith"\r
428                          }\r
429                      }\r
430                  },\r
431                  {\r
432                      "score": 0.8,\r
433                      "document": {\r
434                          "url": "/indexes/people/documents/10",\r
435                          "etag": "7",\r
436                          "content": {\r
437                              "FirstName": "Alan",\r
438                              "LastName": "Smith"\r
439                          }\r
440                      }\r
441                  }\r
442             ]\r
443         }\r
444     }\r
445 \r
446 _Example - Simple search statement with filter and aggregation stanzas_\r
447 \r
448 Assuming the following document set:\r
449 \r
450     {"FirstName": "Will", "LastName": "Smith", "BirthDate": "1968-09-25T00:00:00", "Profession": "Actor"},\r
451     {"FirstName": "Jaden, "LastName": "Smith", "BirthDate": "1998-06-08T00:00:00", "Profession": "Actor"},\r
452     {"FirstName": "Alan, "LastName": "Smith", "BirthDate": "1956-05-21T00:00:00", "Profession": "Artist"},\r
453     {"FirstName": "Wilson", "LastName": "Fisk", "BirthDate": "1962-02-17T00:00:00", "Profession": "Crime Lord"},\r
454     {"FirstName": "Bob", "LastName": "Smith", "BirthDate": "1972-11-05T00:00:00", "Profession": "Plumber"},\r
455     {"FirstName": "Jane", "LastName": "Smith", "BirthDate": "1992-10-15T00:00:00", "Profession": "Accountant"},\r
456     {"FirstName": "John", "LastName": "Doe", "BirthDate": "1981-10-15T00:00:00", "Profession": "Janitor"}\r
457     \r
458 Filter out all people born before Jan 1, 1960, then query the remaining set for people who's last name is 'Smith', with preference to plumbers, and finally count the number of each profession in the resulting set:\r
459 \r
460 Search Statement:\r
461 \r
462     {\r
463         "filter": {\r
464             "all": {\r
465                 { "must": {"range": {"field": "BirthDate", "gte", "1960-01-01T00:00:00"}}}\r
466             }\r
467         },\r
468         \r
469         "queries": [\r
470             {"must": {"match": {"field": "LastName", "value": "Smith"}}},\r
471             {"may": {"match": {"field": "Profession", "value": "Plumber"}}}\r
472         ],\r
473         \r
474         "aggregations": [\r
475                 {\r
476                         "name": "by_profession",\r
477                         "aggregation": {\r
478                             "group-by": {\r
479                                 "field": "Profession"\r
480                             }\r
481                         }\r
482            } \r
483         ] \r
484     }\r
485 \r
486 Response Body:\r
487 \r
488     {\r
489         "searchResult": {\r
490             "totalHits": 4,\r
491             "hits": [\r
492                 {\r
493                      "score": 0.8,\r
494                      "document": {\r
495                          "url": "/indexes/people/documents/8",\r
496                          "etag": "3",\r
497                          "content": {\r
498                              "FirstName": "Bob",\r
499                              "LastName": "Smith",\r
500                              "Profession": "Plumber"\r
501                              "BirthDate": "1972-11-05T00:00:00"\r
502                          }\r
503                      }\r
504                  },\r
505                  {\r
506                      "score": 0.5,\r
507                      "document": {\r
508                          "url": "/indexes/people/documents/10",\r
509                          "etag": "7",\r
510                          "content": {\r
511                              "FirstName": "Will",\r
512                              "LastName": "Smith",\r
513                              "Profession": "Actor",\r
514                              "BirthDate": "1968-09-25T00:00:00"\r
515                          }\r
516                      }\r
517                  },\r
518                  {\r
519                      "score": 0.5,\r
520                      "document": {\r
521                          "url": "/indexes/people/documents/10",\r
522                          "etag": "7",\r
523                          "content": {\r
524                              "FirstName": "Jaden",\r
525                              "LastName": "Smith",\r
526                              "Profession": "Actor",\r
527                              "BirthDate": "1998-06-08T00:00:00"\r
528                          }\r
529                      }\r
530                  },\r
531                  {\r
532                      "score": 0.5,\r
533                      "document": {\r
534                          "url": "/indexes/people/documents/10",\r
535                          "etag": "7",\r
536                          "content": {\r
537                              "FirstName": "Jane",\r
538                              "LastName": "Smith",\r
539                              "Profession": "Accountant",\r
540                              "BirthDate": "1992-10-15T00:00:00"\r
541                          }\r
542                      }\r
543                  }\r
544             ]\r
545         },\r
546         "aggregationResult": {\r
547             "aggregations": [\r
548                 {\r
549                     "name": "by_profession",\r
550                     "buckets": [\r
551                         { "key": "Actor", "count": 2 },\r
552                         { "key": "Plumber", "count": 1 },\r
553                         { "key": "Accountant", "count": 1 }\r
554                     ]\r
555             ]\r
556         }\r
557     }\r
558 \r
559 \r
560 ## API\r
561 \r
562 ### Submit a Search Query\r
563 \r
564 ---\r
565 **URL**\r
566 \r
567     https://{host}:9509/services/search-data-service/v1/search/indexes/{index}/query/\r
568 \r
569 **Method** \r
570 \r
571     POST\r
572 \r
573 **URL Params**\r
574 \r
575     index - The name of the _Index_ to apply the query against.\r
576 \r
577 **Request Header**\r
578 \r
579     Accept          = application/json\r
580     X-TransactionId = Unique id set by client (for logging purposes)\r
581     X-FromAppId     = Application identifier (for logging purposes)\r
582     Content-Type    = application/json\r
583     \r
584 **Request Payload**\r
585 \r
586     Search statement expressed in JSON format (see **Syntax**) \r
587 \r
588 **Success Response**\r
589 \r
590     Code:      200\r
591     Header(s): None\r
592     Body:      JSON format result set.  \r
593     \r
594 **Error Response**\r
595 \r
596     400 - Bad Request\r
597     403 - Unauthorized\r
598     500 - Internal Error\r
599 \r
600 ---\r