Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

String lexicographic range query in Elasticsearch

Is it possible to query Elasticsearch giving it a range of strings?

Something that I'd imagine like:

Sample Mapping:

     {
      "resource" : {
        "properties" : {
          "Title" : {
            "type" : "string"
          },
          "type_" : {
            "index" : "not_analyzed",
            "type" : "string"
          },
           "Summary" : {
            "format" : "dateOptionalTime",
            "type" : "date"
          }
        }
      }
    }

Sample Query:

{
  "size" : 10,
  "query" : {
    "filtered" : {
      "query" : {
        "bool" : {
          "should" : [ {
            "text" : {
              "Title" : {
                "query" : "AAA",
                "type" : "phrase_prefix"
              }
            }
          }, {
            "range" : {
              "Title" : {
                "from" : "BBB",
                "to" : "CCC",
                "include_lower" : true,
                "include_upper" : true
              }
            }
          } ],
          "minimum_number_should_match" : 1
        }
      },
      "filter" : {
        "and" : {
          "filters" : [{
            "or" : {
              "filters" : [ {
                "term" : {
                  "type_" : "personType"
                }
              } ]
            }
          } ]
        }
      }
    }
  }
}

Data Indexed: Resources with Titles 'AAA', 'BBB', 'CCC', 'DDD'

Result Resource with Title 'AAA' (range didn't select 'BBB' and 'CCC')

Any help appreciated

like image 959
Queequeg Avatar asked Jun 12 '26 13:06

Queequeg


2 Answers

Yes, it is possible. The RangeQuery provided by the elasticsearch query DSL internally uses the lucene TermRangeQuery for field of type string. On the other hand, it uses the lucene NumericRangeQuery for field of type number/date.

like image 136
javanna Avatar answered Jun 14 '26 04:06

javanna


By default ElasticSearch keeps all indexed data lowercase. It does not lowercase the queries, though. Great.

To wrap up: after sending the queries (from and to values) all in lowercase the range searching works like a charm.

like image 38
Queequeg Avatar answered Jun 14 '26 02:06

Queequeg



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!