Elasticsearch ip range query

Dear,

I set mapping below

PUT iptest
{
   "mappings": {
      "addy": {
          "properties":{
             "ips": { "type": "ip"}
          }
      }
   }
}

And insert data:

PUT iptest/addy/1?refresh
{"ips": [ "10.230.208.88", "0.0.0.0"]}

PUT iptest/addy/2?refresh
{"ips": ["10.0.2.15","192.168.56.106"]}

Then query (1):

GET iptest/_search
{
	"query": {
		"bool": {
			"filter": [{
				"bool": {
					"must": [{
						"range": {
							"ips": {
								"gte": "10.52.51.14"
							}
						}
					},
					{
						"range": {
							"ips": {
								"lte": "10.52.51.34"
							}
						}
					}]
				}
			}]
		}
	},
	"from": 0,
	"size": 100,
	"_source": ["ips"]
}

But results is:

"hits" : [
      {
        "_index" : "iptest",
        "_type" : "addy",
        "_id" : "2",
        "_score" : 0.0,
        "_source" : {
          "ips" : [
            "10.0.2.15",
            "192.168.56.106"
          ]
        }
      },
      {
        "_index" : "iptest",
        "_type" : "addy",
        "_id" : "1",
        "_score" : 0.0,
        "_source" : {
          "ips" : [
            "10.230.208.88",
            "0.0.0.0"
          ]
        }
      }
    ]

I see "10.0.2.15" <= "10.52.51.34" AND "192.168.56.106" >= "10.52.51.14" ==> matching.
I want a element of ips is matching for this condition: "10.0.2.15" <= ip <= "10.52.51.34".

Thanks so much.

Your current query searches for a document where any IP matches the first clause and any IP matches the second clause. Both clauses or not necessarily applied to the same IP. What you want to do instead is rewrite your query to something like this:

GET iptest/_search
{
  "query": {
    "bool": {
      "filter": [
        {
          "range": {
            "ips": {
              "gte": "10.52.51.14",
              "lte": "10.52.51.34"
            }
          }
        }
      ]
    }
  },
  "from": 0,
  "size": 100,
  "_source": [
    "ips"
  ]
}

That way, the range is applied to one specific IP.

1 Like

Thanks abdon.
I tried successfully.

Is there another way to use mapping?

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