Skip to content Skip to sidebar Skip to footer

How Do I Tell An Elasticsearch Multi-match Query That I Want Numeric Fields, Stored As Strings, To Return Matches With Numeric Strings?

I am writing a Flask app and I am using elasticsearch. Here is search.py: from flask import current_app def query_object(index, fields, query, page, per_page, fuzziness=0): se

Solution 1:

The issue is happening due to the use of fuzziness param on the numeric data type and then use of lenient true to make it work by as it removes format-based errors, such as providing a text query value for a numeric field, are ignored. mentioned in this link.

Below is the error which you get while trying to use fuzziness on numeric data types.

reason": "Can only use fuzzy queries on keyword and text fields - not on [age] which is of type [integer]"

And when you add "lenient" : true, then the above error goes but doesn't return any document.

To make it work, simply remove fuzziness and lenient param from your search query and it should work, as Elasticsearch automatically converts valid string to numeric and vice versa as explained in coerce article.

Working example to show it using REST API

Index def

{"mappings":{"properties":{"age":{"type":"integer"}}}}

Index sample doc

{
  "age" : "25" --> note use of `""`, sending it as string
}

{
  "age" : 28 :- note sending numneric value
}

A search query in string format

{
    "query": {
        "bool": {
            "must": [
                {
                    "multi_match": {
                        "query": "28", --> note string format"fields": [
                            "age"--> note you can add more fields
                        ]
                    }
                }
            ]
        }
    }
}

Search result

"hits":[{"_index":"so_numberic","_type":"_doc","_id":"1","_score":1.0,"_source":{"program_number":"123456789","age":"28"}}]

Search query in numeric format

{
    "query": {
        "match" : { --> query on single field."age" : {
                "query" : 28--> note numeric format
            }
        }
    }
}

Result

"hits":[{"_index":"so_numberic","_type":"_doc","_id":"1","_score":1.0,"_source":{"program_number":"123456789","age":"28"}}]

Showing your fuzziness and lenient doesn't bring any result as explained earlier.

Search query

{"query":{"match":{"age":{"query":28,"fuzziness":2,"lenient":true}}}}

Result

{
    "took": 1,
    "timed_out": false,
    "_shards": {
        "total": 1,
        "successful": 1,
        "skipped": 0,
        "failed": 0
    },
    "hits": { --> note 0 results.
        "total": {
            "value": 0,
            "relation": "eq"
        },
        "max_score": null,
        "hits": []
    }
}

Post a Comment for "How Do I Tell An Elasticsearch Multi-match Query That I Want Numeric Fields, Stored As Strings, To Return Matches With Numeric Strings?"