Reputation: 633
I have some records with id property so I need to search my id field using Elasticsearch. But the user doesn't have exact id so Once the user tries with a partial number if it matches partially should return the result.
For an example, Id is 1234 once I type 12 should return this record Any idea of how to do string contains (*) behavior for numeric values?
Upvotes: 1
Views: 2407
Reputation: 32376
if you care about the prefix search ie for id 1234
only when user start the search for 12
it should return id and not for 23
, then it will be more performant and can easily be implemented using the perfix query in Elasticsearch.
If you want 1234
even when the user misses beginning char and search for 23
, then you can need to create a custom analyzer using n-gram tokenizer, which will create tokens like 12
, 23
, 34
, 123
, 234
like so that you can provide infix search as well.
Note: Both prefix queries
and n-gram tokenizer
are not applicable to a numeric field. you need to store your user id in the text field to make it work.
Working example for n-gram tokenizer
as requested in comment
Index def
{
"settings": {
"index.max_ngram_diff": 10,
"analysis": {
"filter": {
"autocomplete_filter": {
"type": "ngram",
"min_gram": 1,
"max_gram": 10
}
},
"analyzer": {
"autocomplete": {
"type": "custom",
"tokenizer": "standard",
"filter": [
"lowercase",
"autocomplete_filter"
]
}
}
}
},
"mappings": {
"properties": {
"uid": {
"type": "text",
"analyzer": "autocomplete",
"search_analyzer" : "standard"
}
}
}
}
Index sample doc
{
"uid" : "1234"
}
**Search query for 12
**
{
"query": {
"match" : {
"uid" : {
"query" : "12"
}
}
}
}
Result
"hits": [
{
"_index": "intdata",
"_type": "_doc",
"_id": "1",
"_score": 0.45532417,
"_source": {
"uid": "1234"
}
}
]
Similarly, it would return result for 23
, 123
, 34
etc
Upvotes: 1