Skip to content

Instantly share code, notes, and snippets.

@justahero
Last active December 5, 2018 10:42
Show Gist options
  • Save justahero/c308b52898f70ba385336b629b98720d to your computer and use it in GitHub Desktop.
Save justahero/c308b52898f70ba385336b629b98720d to your computer and use it in GitHub Desktop.
Elasticsearch Percolator Query example

Percolator Query

This setup shows how to use a percolator query, for more details see Percolator Query documentation.

The following setup was tested with Elasticsearch 6.5.

Create a new index with a given mapping, the document only accepts a message field

curl -X PUT 'http://localhost:9200/percolator' -H 'Content-Type: application/json' -d '{
  "mappings": {
    "keywords": {
      "_source": {
        "enabled": true
      },
      "properties": {
        "message": {
          "type": "text"
        },
        "query": {
          "type": "percolator"
        }
      }
    }
  }
}'

Register a percolator query, a bool query where both match phrase queries need to be found.

curl -X POST 'http://localhost:9200/percolator/keywords/1?refresh' -H 'Content-Type: application/json' -d '{  
  "query": {
    "bool": {
      "must": [
        {
          "match_phrase": {
            "message": {
              "query": "red car"
            }
          }
        },
        {
          "match_phrase": {
            "message": {
              "query": "blue car"
            }
          }
        }
      ]
    }
  }
}'

Then run the query to be found by percolator query, with appropriate highlight:

curl -X GET 'http://localhost:9200/percolator/_search?pretty=true' -H 'Content-Type: application/json' -d '{
  "query": {
    "percolate": {
      "field": "query",
      "documents": [
        {
          "message": "i see a blue car and a red car"
        }
      ]
    }
  },
  "highlight": {
    "fields": {
      "message": {
        "type": "unified"
      }
    },
    "pre_tags": [
      "<span class=\"highlight\">"
    ],
    "post_tags": [
      "</span>"
    ]
  }
}'

Note that the result highlights the words in the phrase separately. This is known behaviour and likely to change in the future, see elastic/elasticsearch#29561 for more details

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment