Elasticsearch Full Text Phrase Matching Queries with cURL and Python

Spread the love

In this blog post, you will learn how to search for phrases in Elasticsearch documents. A phrase matching query will search for a phrase, such as “the quick brown fox”, instead of individual terms, such as “fox” or “dog”.

Phrase Matching Queries with cURL

The following query will search for a phrase in documents with the JavaScript Object Notation (JSON) property “fulltext” (“Match phrase query”, n.d.).

{
    "query" : { 
        "match_phrase" : { 
            "fulltext" : "the quick brown fox jumped" 
        }
    } 
}

The following cURL command will perform a phrase match query on an index called docs (Notice: the cURL command accesses Elasticsearch securely. For more information on securely accessing Elasticsearch, you can read my blog post on Securely and Programmatically Accessing Elasticsearch with curl and Python):

curl -H "Content-Type: application/json" --cacert config/certs/http_ca.crt -u elastic:I4e2IMlRZNlTDokKEjy9 -XGET https://localhost:9200/docs/_search -d '{ "query" : { "match_phrase" : { "fulltext" : "the quick brown fox jumped" } } }'

The output for the execution of the cURL command are as follows:

{
  "took": 69,
  "timed_out": false,
  "_shards": {
    "total": 1,
    "successful": 1,
    "skipped": 0,
    "failed": 0
  },
  "hits": {
    "total": {
      "value": 1,
      "relation": "eq"
    },
    "max_score": 2.2867923,
    "hits": [
      {
        "_index": "docs",
        "_id": "RGL2T4wBH7bC1ympqTU1",
        "_score": 2.2867923,
        "_source": {
          "fulltext": "the quick brown fox jumped over the lazy dog"
        }
      }
    ]
  }
}

As you can see, the query returned the following document:

{
    "fulltext": "the quick brown fox jumped over the lazy dog"
}

Phrase Matching Queries with Python

The following python script performs a phrase matching query on an Elasticsearch instance:

from elasticsearch import Elasticsearch

ELASTIC_PASSWORD = "I4e2IMlRZNlTDokKEjy9"

def main():
    es = Elasticsearch("https://localhost:9200",
        ca_certs="/Users/gcdrocella/elasticsearch-8.11.2/config/certs/http_ca.crt", 
        basic_auth=("elastic", ELASTIC_PASSWORD))
    
    resp = es.search(index="docs", query= {
        "match_phrase" : {
            "fulltext" : {
                "query" : "quick fox",
            }
        }
    })

    print(resp)


main()

In this blog post, you learned how to perform phrase matching queries in Elasticsearch with cURL and python.

Thanks for reading! For more blog posts just like this, subscribe, share, and buy me a coffee!

Subscribe

* indicates required

Intuit Mailchimp

References

Match phrase query. (n.d.). Elastic.Co. Retrieved December 11, 2023, from https://www.elastic.co/guide/en/elasticsearch/reference/current/query-dsl-match-query-phrase.html


Posted

in

,

by