How to build an Elasticsearch query that will take into account the distance between words?

I'm running with elasticsearch:7.6.2

I have an index with 4 simple documents:

    PUT demo_idx/_doc/1
      "content": "Distributed nature, simple REST APIs, speed, and scalability, Elasticsearch is the central component of the Elastic Stack, the end"

    PUT demo_idx/_doc/2
      "content": "Distributed tmp nature, simple REST APIs, speed, and scalability"

    PUT demo_idx/_doc/3
      "content": "Distributed nature, simple REST APIs, speed, and scalability"

    PUT demo_idx/_doc/4
      "content": "Distributed tmp tmp nature"

I want to search for the text: distributed nature and get the following results order:

Doc id: 3 
Doc id: 1
Doc id: 2
Doc id: 4

i.e documents with exact match (doc 3 & doc 1) will be displayed before documents with small slop (doc 2) and documents with big slop match will be last displayed (doc 4)

I have tried the following search query:

"query": {
            "bool": {
                        "match_phrase": {
                            "content": {
                                "query": query,
                                "slop": 2

But it didnt gave me the required results.

I got the following results:

Doc id: 3  ,Score: 0.22949813
Doc id: 4  ,Score: 0.15556586
Doc id: 1  ,Score: 0.15401536 
Doc id: 2  ,Score: 0.14397088

How can I write the query in order to get the results I want to ?

The only way I can think of doing this is having many queries (ORed) with different slops set where you change the constant_score boost to be larger when the slop is lower.

This topic was automatically closed 28 days after the last reply. New replies are no longer allowed.