Elasticsearch match exact term

2019-09-14 07:55发布

I have an Elasticsearch repo and a aplication that create documents for what we call 'assets'. I need to prevent users to create 'assets' with the same 'title'.

When the user tries to create an 'asset' I am querying the repo with the title and if there is a match an error message is shown to the user.

My problem is that when I query the title I am getting multiple results (for similar matches).

This is my query so far:

GET assets-1/asset/_search
{
  "query": {
    "match": {
      "title": {
        "query": "test",
        "operator": "and"
      }
    }
  }
}

I have many records with title: 'test 1', 'test 2', 'test bla' and only one with the title 'test'.

But I am getting all of the above.

Is there any condition or property I have to add to the query so I will exact match the term?

1条回答
一夜七次
2楼-- · 2019-09-14 08:24

Your title field is probably analyzed and thus the test token will match any title containing that token.

In order to implement an exact match you need to have a not_analyzed field and do a term query on it.

You need to change the mapping of your title field to this:

curl -XPUT localhost:9200/assets-1/_mapping/asset -d '{
   "asset": {
      "properties": {
         "title": {
            "type": "string",
            "fields": {
               "raw": {
                   "type": "string",
                   "index": "not_analyzed"
               }
            }
         }
      }
   }
}'

Then you need to reindex your data and you'll then be able to run an exact match query like this:

curl -XPOST localhost:9200/assets-1/asset/_search -d '{
   "query": {
      "term": {
         "title.raw": "test"
      }
   }
}'
查看更多
登录 后发表回答