Mohammad Banisaeid
Mohammad Banisaeid

Reputation: 2626

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.

Upvotes: 4

Views: 11791

Answers (3)

Ostati
Ostati

Reputation: 4741

Elastic uses Lucene's Regex engine, which doesn't support everything. To solve your particular problem however, you can use wildcard search or regexp search like so:

GET /products/_search
{
  "query": {
    "wildcard": {
      "description.keyword": {
        "value": "*able"
      }
    }
  }
}

GET /products/_search
{
  "query": {
    "regexp":{
      "description.keyword": {
        "value": "[a-zA-Z0-9]+fox",
        "flags": "ALL", 
        "case_insensitive": true
      }
    }
  }
}

Upvotes: 1

Adam T
Adam T

Reputation: 1701

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"
        }
    }
}

Upvotes: 1

LeBigCat
LeBigCat

Reputation: 1770

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",
            }
        }

Upvotes: 1

Related Questions