Search for name(text) with spaces in elasticsearch
You can use the multi field type, a bool query and the custom boost factor query to solve this problem.
Mapping:
{
"mappings" : {
"user" : {
"properties" : {
"name": {
"type": "multi_field",
"fields": {
"name": { "type" : "string", "index": "analyzed" },
"exact": { "type" : "string", "index": "not_analyzed" }
}
}
}
}
}
}
Query:
{
"query": {
"bool": {
"must": [
{
"match": {
"name": "Maaz Tariq"
}
}
],
"should": [
{
"custom_boost_factor": {
"query": {
"term": {
"name.exact": "Maaz Tariq"
}
},
"boost_factor": 15
}
},
{
"custom_boost_factor": {
"query": {
"prefix": {
"name.exact": "Maaz Tariq"
}
},
"boost_factor": 10
}
},
{
"custom_boost_factor": {
"query": {
"match_phrase": {
"name": {
"query": "Maaz Tariq",
"slop": 0
}
}
},
"boost_factor": 5
}
}
]
}
}
}
edit:
As pointed out by javanna, the custom_boost_factor
isn't needed.
Query without custom_boost_factor
:
{
"query": {
"bool": {
"must": [
{
"match": {
"name": "Maaz Tariq"
}
}
],
"should": [
{
"term": {
"name.exact": {
"value": "Maaz Tariq",
"boost": 15
}
}
},
{
"prefix": {
"name.exact": {
"value": "Maaz Tariq",
"boost": 10
}
}
},
{
"match_phrase": {
"name": {
"query": "Maaz Tariq",
"slop": 0,
"boost": 5
}
}
}
]
}
}
}