Mapping a Percolator field
The Percolator is a special type of field that makes it possible to store an Elasticsearch query inside the field and use it in a percolator
query.
The Percolator can be used to detect all the queries that match a document.
Getting ready
You will need an up-and-running Elasticsearch installation, as we described in the Downloading and installing Elasticsearch recipe of Chapter 1, Getting Started.
To execute the commands in this recipe, you can use any HTTP client, such as curl (https://curl.haxx.se/), Postman (https://www.getpostman.com/), or similar. I suggest using the Kibana console, which provides code completion and better character escaping for Elasticsearch.
How to do it...
To map a percolator
field, follow these steps:
- We want to create a Percolator that matches some text in a
body
field. We can define the mapping like so:PUT test-percolator { "mappings": { "properties": { "query": { "type": "percolator" }, "body": { "type": "text" } } } }
- Now, we can store a document with a
percolator
query inside it, as follows:PUT test-percolator/_doc/1?refresh { "query": { "match": { "body": "quick brown fox" }}}
- Now, let's execute a search on it, as shown in the following code:
GET test-percolator/_search { "query": { "percolate": { "field": "query", "document": { "body": "fox jumps over the lazy dog" } } } }
- This will result in us retrieving the hits of the stored document, as follows:
{ ... truncated... "hits" : [ { "_index" : "test-percolator", "_id" : "1", "_score" : 0.13076457, "_source" : { "query" : { "match" : { "body" : "quick brown fox" } } }, "fields" : { "_percolator_document_slot" : [0] } } ] } }
How it works…
The percolator
field stores an Elasticsearch query inside it.
Because all the Percolators are cached and are always active for performances, all the fields that are required in the query must be defined in the mapping of the document.
Since all the queries in all the Percolator documents will be executed against every document, for the best performance, the query inside the Percolator must be optimized so that they're executed quickly inside the percolator
query.