Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Elasticsearch: Look for a term at the end of text

I'm indexing the following documents in Elasticsearch 5.x:

{
    "id": 1
    "description": "The quick brown fox"
}

{
    "id": 2
    "description": "The fox runs fast"
}

If I search for the word "fox" in these documents, I will get both of them. How can I find documents that their description field ends with the word "fox"? In the above example, I am looking the one with id=1

If possible, I prefer to do this with a Query String.

like image 626
Mohammad Banisaeid Avatar asked Oct 27 '25 14:10

Mohammad Banisaeid


2 Answers

Well regex should work. Note if you have to look for endwith a lot of time, reindex using a analyzer will be the best (https://discuss.elastic.co/t/elasticsearch-ends-with-word-in-phrases/60473)

"regexp":{
            "id": {
                "value": "*fox",
            }
        }
like image 50
LeBigCat Avatar answered Oct 30 '25 14:10

LeBigCat


Make sure your index mapping includes a keyword field for the description. For example:

PUT my_index
{
  "mappings": {
    "_doc": {
      "properties": {
        "description": {
          "type": "text",
          "fields": {
            "keyword": {
              "type": "keyword",
              "ignore_above": 256
            }
          }
        },
        "id": {
          "type": "long"
        }
      }
    }
  }
}

Add the documents:

POST my_index/_doc
{
    "id": 1,
    "description": "The quick brown fox"
}

POST my_index/_doc
{
    "id": 2,
    "description": "The fox runs fast"
}

And use a query string like this:

GET /my_index/_search
{
    "query": {
        "query_string" : {
            "default_field" : "description.keyword",
            "query" : "*fox"
        }
    }
}
like image 37
Adam T Avatar answered Oct 30 '25 14:10

Adam T