Home > Enterprise >  Is there a `eq` operator in elasticsearch for int type?
Is there a `eq` operator in elasticsearch for int type?

Time:06-09

I have a document whose has a field saleAmount which is long type defined in the index. I'd like to find the document based on this field to equal to an input value but ES doesn't have eq operator. What I have to do is:

GET indexname/_search
{
  "query": {
    "range": {
      "saleAmount": {"gte": 801, "lte": 801}
    }
  }
}

The above query works fine but it doesn't look great. I wonder what the best way to compare a number value in Elasticsearch?

CodePudding user response:

You can simply use the term query, below is the working example

Index sample data with default mapping as Elasticsearch creates long field for numeric data.

PUT <your-lasticsearch-index>/_doc/1 

{
    "price" : 801
}

PUT <your-lasticsearch-index>/_doc/2

{
    "price" : 802
}

Search query using term on price field.

{
    "query" : {
        "term" : {
            "price" : 801
        }
    }
}

Search result bring only one document with price eq to 801.

 "hits": [
            {
                "_index": "number_eq",
                "_id": "1",
                "_score": 1.0,
                "_source": {
                    "price": 801
                }
            }
        ]

Waring : As mentioned by @Val in the comment, Numeric fields are not optimized for terms query, and for better performance we should always use range queries on numeric fields.

  • Related