Scoring range queries by range size

(Aditya Prasad) #1

I have a field with type ip_range. When I query for an IP address, I'd like to have the results returned in the order of most precise range to least. Is there a simple way to accomplish this? Perhaps I overlooked something obvious in the docs.


(Christoph) #2

Can you give a concrete example of how your query looks like, some sample documents and the order you want them to score?

(Aditya Prasad) #3

Sure! The query is like this:

GET /prefix/_search
  "query" : {
    "term": {
      "key_prefix": {
        "value": ""

And the results are (approximately) like this:

        "_index": "prefix",
        "_type": "doc",
        "_id": "rcFIFGcBaGTwZcx4YKxh",
        "_score": 1,
        "_source": {
          [ ... a bunch of string fields ...],
          "key_prefix": "",

Notice that the CIDR contains But is more precise (it is a range of size 2^12 vs 2^24), and more precisely still (it has size 1). I would like them returned in order of range size.

Does that make sense? Please let me know if you need more information.

(Aditya Prasad) #4

Any thoughts?

(Aditya Prasad) #5

Ping :slight_smile:

(Aditya Prasad) #6


(Christoph) #7


unfortunately both the "term" and also the "range" query on "ip_range" fields seem to do only constant scoring (also known as filtering), so in order to sort on the precision of the range I'd probably store the cidr suffix alongside the range in a separate field and sort by that. Would that work for you use case?

(Aditya Prasad) #8

Hey that's a neat and simple solution! I think it ought to work. Thank you for looking into this for me!

(system) closed #9

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