Reputation: 2626
I'm indexing the following documents in Elasticsearch 5.x:
{
"id": 1
"description": "The quick brown fox"
}
{
"id": 2
"description": "The fox runs fast"
}
If I search for the word "fox"
in these documents, I will get both of them.
How can I find documents that their description
field ends with the word "fox"
? In the above example, I am looking the one with id=1
If possible, I prefer to do this with a Query String.
Upvotes: 4
Views: 11791
Reputation: 4741
Elastic uses Lucene's Regex engine, which doesn't support everything. To solve your particular problem however, you can use wildcard search or regexp search like so:
GET /products/_search
{
"query": {
"wildcard": {
"description.keyword": {
"value": "*able"
}
}
}
}
GET /products/_search
{
"query": {
"regexp":{
"description.keyword": {
"value": "[a-zA-Z0-9]+fox",
"flags": "ALL",
"case_insensitive": true
}
}
}
}
Upvotes: 1
Reputation: 1701
Make sure your index mapping includes a keyword field for the description. For example:
PUT my_index
{
"mappings": {
"_doc": {
"properties": {
"description": {
"type": "text",
"fields": {
"keyword": {
"type": "keyword",
"ignore_above": 256
}
}
},
"id": {
"type": "long"
}
}
}
}
}
Add the documents:
POST my_index/_doc
{
"id": 1,
"description": "The quick brown fox"
}
POST my_index/_doc
{
"id": 2,
"description": "The fox runs fast"
}
And use a query string like this:
GET /my_index/_search
{
"query": {
"query_string" : {
"default_field" : "description.keyword",
"query" : "*fox"
}
}
}
Upvotes: 1
Reputation: 1770
Well regex should work. Note if you have to look for endwith a lot of time, reindex using a analyzer will be the best (https://discuss.elastic.co/t/elasticsearch-ends-with-word-in-phrases/60473)
"regexp":{
"id": {
"value": "*fox",
}
}
Upvotes: 1