Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to execute an IP Range Query/Filter

I am trying to get an IP range query to work over a set of documents, and am getting no results.

Mapping (I've tried both analyzed and not_analyzed):

   "mappings": {
      "addy": {
         "properties": {
            "add": {
               "type": "ip",
               "not_analyzed":"true"
            }
         }
      }
   }

The data looks like this (many instances of this with varying values)

   "_source": {
       "add": "192.168.1.15"
   }

Now, I went looking at the official ES docs, but there was not IP range example, but I found one on the Git , which didn't work. It looks as follows:

    "query": {
        "query_string": {
           "default_field": "add",
           "query": "add:[192.168.1.5 TO 192.168.1.15]"
        }
    }

The above threw some encourage parse errors when I was fat fingering my fields and addresses, but in the end returned no results.

I also tried standard range syntax:

"filter": {
    "range": {
       "add": {
          "from": "192.168.1.5",
          "to": "192.168.1.25"
       }
    }
}

Which also returned no results. How do I query a range of IP addresses?

like image 454
IanGabes Avatar asked Feb 09 '23 12:02

IanGabes


1 Answers

The ip type doesn't take any not_analyzed setting, that's only for string fields. Anyway, I've been able to recreate your index like this:

curl -XPUT localhost:9200/addies -d '{
   "mappings": {
      "addy": {
          "properties":{
             "add": { "type": "ip"}
          }
      }
   }
}'

Then I've created a couple sample documents like this:

curl -XPUT localhost:9200/addies/addy/1 -d '{"add": "192.168.1.100"}'
curl -XPUT localhost:9200/addies/addy/2 -d '{"add": "192.168.1.101"}'
curl -XPUT localhost:9200/addies/addy/3 -d '{"add": "192.168.1.102"}'
curl -XPUT localhost:9200/addies/addy/4 -d '{"add": "192.168.1.110"}'

And finally, using a query_string query I could retrieve only the first three documents like this:

curl -XPOST localhost:9200/addies/addy/_search -d '{
  "query": {
    "query_string": {
      "query": "add:[192.168.1.100 TO 192.168.1.102]"
    }
  }
}'

UPDATE:

Please note that the following range query also works fine and returns the same results:

curl -XPOST localhost:9200/addies/addy/_search -d '{
  "query": {
    "range": {
      "add": {
        "gte": "192.168.1.100",
        "lte": "192.168.1.102"
      }
    }
  }
}'
like image 83
Val Avatar answered Feb 12 '23 11:02

Val