Convert string to ip in painless processor

Hello,

Is there a way to convert a string to an ip address in a painless processor?

Regards Hans

If your index has the field mapped as an IP address, it should be able to accept IP addresses as strings. Here's a quick contrived example from Kibana dev tools:

# create an index with an IP field mapping
PUT ip-docs
{
  "mappings": {
    "properties": {
      "ip_addr": {
        "type": "ip"
      }
    }
  }
}

# a processor that splits a column-delimited field, assuming an IP address there
PUT _ingest/pipeline/ip_grabber
{
  "processors": [
    {
      "script": {
        "description": "extract IP address",
        "lang": "painless",
        "source": """
            String[] envSplit = ctx['env'].splitOnToken(params['delimiter']);
            ctx['ip_addr'] = envSplit[params['position']].trim();
          """,
        "params": {
          "delimiter": "|",
          "position": 1
        }
      }
    }
  ]
}

# send a document in the expected format
POST ip-docs/_doc?pipeline=ip_grabber
{
  "env": "es01-prod|192.0.0.1"
}

# we can search on the IP
GET ip-docs/_search
{
  "query": {
    "range": {
      "ip_addr": {
        "gte": "192.0.0.0",
        "lte": "192.0.0.2"
      }
    }
  }
}

If you want validation and more control over parsing failures, you can use a convert processor after your script processor:

POST _ingest/pipeline/_simulate
{
  "pipeline": {
    "processors": [
      {
        "script": {
          "description": "extract IP address",
          "lang": "painless",
          "source": """
            String[] envSplit = ctx['env'].splitOnToken(params['delimiter']);
            ctx['ip_addr'] = envSplit[params['position']].trim();
          """,
          "params": {
            "delimiter": "|",
            "position": 1
          }
        }
      },
      {
        "convert": {
          "field": "ip_addr",
          "type": "ip"
        }
      }
    ]
  },
  "docs": [
    {
      "_source": {
        "env": "es01-prod|192.invalid.ip.1"
      }
    }
  ]
}

Thanks!

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