PeteyPabPro
PeteyPabPro

Reputation: 849

How to match fields starting with phrase in Elasticsearch

Say I have an analyzed field, and I want to do a search that matches on that field if the field starts with the supplied phrase. For example, say I have two documents, each with a single field:

doc1 : {
    name: "the dog is happy"
}

doc2: {
    name: "happy the dog is"
}

Say my query string is "the dog is". I want to match doc1 and not doc2. How can I do this?

Thanks!

Upvotes: 0

Views: 5941

Answers (2)

Kaushik J
Kaushik J

Reputation: 1072

GET /_search
{
    "query": {
        "prefix": {
            "user": {
                "value": "the dog is"
            }
        }
    }
}

Also,
To Speed up prefix queries You can speed up prefix queries using the index_prefixes mapping parameter. If enabled, Elasticsearch indexes prefixes between 2 and 5 characters in a separate field. This lets Elasticsearch run prefix queries more efficiently at the cost of a larger index.

Upvotes: -1

Michael Stockerl
Michael Stockerl

Reputation: 749

If you mark the beginning of each sentence in your documents with a special token, you can do a phrase matching query:

So if you index your documents like that

doc1 : {
    name: "START the dog is happy"
}

doc2: {
    name: "START happy the dog is"
}

You get the desired result with this query:

POST /test/test/_search
{
  "query": {
    "match_phrase": {
      "name": "START the dog is"
    }
  }
}

Upvotes: 4

Related Questions