How to ignore malformed query for IP property

Hi there, I have an Elasticsearch index whose mapping has two properties - one is of type keyword and the other is of type ip:

"mappings": {
            "properties": {
                "user_id": {
                    "type": "keyword"
                },
                "ip_address": {
                    "type": "ip"
                }
           }
}

The documents in this index contain valid IP addresses in the ip_address property. I'd like to issue a search query for this index that searches for both fields with the same query text, as shown below. The search query text (foo in the example below) could either be found in the user_id property or it could be an IP:

/* Here, foo is a sample query text - it could be a user ID or an IP */
"query": {
        "bool": {
            "should": [
                {
                    "term": {
                        "user_id": {
                            "value": "foo"
                        }
                    }
                },
                {
                    "term": {
                        "ip_address": {
                            "value": "foo"
                        }
                    }
                }
            ]
        }
    }

If I run the above query as-is, I get the error below, which makes sense as foo is not a valid IP. Is there a way I can supply both user_id and ip_address properties in the query and avoid this error when the query text is not a valid IP? In case the query text is not a valid IP, the search can simply "ignore" the ip_address property and just search in the user_id property.

    "error": {
        "root_cause": [
            {
                "type": "query_shard_exception",
                "reason": "failed to create query: 'foo' is not an IP string literal.",
            }
        ],
        "type": "search_phase_execution_exception",
       ...

I'd like to be able to supply both user_id and ip_address properties in the query without worrying about whether the query text is a valid IP or not. Alternatively, I could validate whether the query text is a valid IP and if it isn't, exclude the ip_address property in the query - but I'd prefer to not do this if possible.

While this might not work with the term, maybe try with the match query using the lenient field. I don't necessarily recommned this though :slight_smile: