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.

Thanks!


(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": "127.0.0.1"
      }
    }
  }
}

And the results are (approximately) like this:

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

Notice that the CIDR 127.0.0.0/8 contains 127.0.0.1. But 127.0.0.0/20 is more precise (it is a range of size 2^12 vs 2^24), and 127.0.0.1/32 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

@cbuescher


(Christoph) #7

Hi,

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!