Elastic search - a search string that contains spaces
I'm looking for an ElasticSearch query that will provide an exact match for a string that contains spaces.
for example - I want to search for a word, for example "XYZ Company Solutions". I tried a query with a query, but it gives me all the records regardless of the search result. Also I read in the post and found that we need to add some mappings for the field. I tried the "Not_Analyzed" analyzer on the field, but it still didn't work.
If anyone has a complete example or steps, can you share with me?
Thanks in advance.
Thank you, Samir
source to share
Since you didn't post your code, it's hard to tell what's wrong, but "index": "not_analyzed"
in your mapping is the correct way to handle this.
Here's a simple working example. First, I create a mapping that uses "index": "not_analyzed"
:
PUT /test_index
{
"mappings": {
"doc": {
"properties": {
"name":{
"type": "string",
"index": "not_analyzed"
}
}
}
}
}
Then add some docs for testing
POST /test_index/doc/_bulk
{"index":{"_id":1}}
{"name":"XYZ Company Solutions"}
{"index":{"_id":2}}
{"name":"Another Company"}
Now I can get the document I want with a simple term query :
POST /test_index/doc/_search
{
"query": {
"term": {
"name": {
"value": "XYZ Company Solutions"
}
}
}
}
...
{
"took": 1,
"timed_out": false,
"_shards": {
"total": 1,
"successful": 1,
"failed": 0
},
"hits": {
"total": 1,
"max_score": 1,
"hits": [
{
"_index": "test_index",
"_type": "doc",
"_id": "1",
"_score": 1,
"_source": {
"name": "XYZ Company Solutions"
}
}
]
}
}
A term filter or even query query will also work in this case.
Here's the code I used to test it:
http://sense.qbox.io/gist/90fcc7f7a88d58f098c50d5aaf0315fdf06e9e9a
source to share
PUT /index_1
{
"settings": {
"analysis": {
"normalizer": {
"lowercase_normalizer": { "type": "custom", "char_filter": [], "filter": ["lowercase"]}
}
}
},
"mappings": {
"doc_type": {
"properties": {
"name":{"type": "keyword", "normalizer": "lowercase_normalizer"}
}
}
}
}
I used the above settings and mapping to determine the index. Then dragged multiple values into the database
POST index_1/doc_type/1
{
"name" : "a b c"
}
POST index_1/doc_type/1
{
"name" : "a c"
}
POST index_1/doc_type/1
{
"name" : "a b"
}
Now if we search for individual letters in the name field of the above index we get nothing
GET index_1/doc_type/_search
{
"query" :
{"match": {"name": "A"}}
}
GET index_1/doc_type/_search
{
"query" :
{"match": {"name": "b"}}
}
but if we are looking for
GET index_1/doc_type/_search
{
"query" :
{"match": {"name": "A B C"}}
}
we will get a match
It helps to search for the full keyword while avoiding senstivity.
source to share