简体   繁体   中英

Unexpected result of Elastic term query

I have Elastic 2.4 running on http://localhost:9200 only for test.

Setup

As fresh start, I created 1 and only 1 item in the index.

$ curl -s -XPUT "http://localhost:9200/movies/movie/1" -d'
{
    "title": "The Godfather",
    "director": "Francis Ford Coppola",
    "year": 1972,
    "genres": ["Crime", "Drama"]
}'

Returns

{"_index":"movies","_type":"movie","_id":"1","_version":3,"_shards":{"total":2,"successful":1,"failed":0},"created":false}

I then run this command to confirm the index works:

$ curl -s -XPOST "http://localhost:9200/movies/_search" -d'
{
    "query": {
        "query_string": {
            "query": "Godfather"
        }
    }
}'

Returns

{"took":8,"timed_out":false,"_shards":{"total":5,"successful":5,"failed":0},"hits":{"total":1,"max_score":0.095891505,"hits":[{"_index":"movies","_type":"movie","_id":"1","_score":0.095891505,"_source":
{
    "title": "The Godfather",
    "director": "Francis Ford Coppola",
    "year": 1972,
    "genres": ["Crime", "Drama"]
}}]}}

The Problem

I tried to run term query like this:

$ curl -s -XPOST "http://localhost:9200/movies/_search" -d'
{
    "query": {
        "term": {"title": "The Godfather"}
    }
}'

I was expected to get 1 result, instead I got this:

{"took":1,"timed_out":false,"_shards":{"total":5,"successful":5,"failed":0},"hits":{"total":0,"max_score":null,"hits":[]}}

What did I got wrong?

Either match_phrase like jay suggested or you need to create a not_analyzed sub-field (eg title.raw ), like this:

$ curl -s -XPUT "http://localhost:9200/movies/_mapping/movie" -d'
{
    "properties": {
        "title": {
            "type": "string",
            "fields": {
               "raw": {
                   "type": "string",
                   "index": "not_analyzed"
               }
            }
        }
    }
}'

Then you can reindex your document to populate the title.raw :

$ curl -s -XPUT "http://localhost:9200/movies/movie/1" -d'
{
    "title": "The Godfather",
    "director": "Francis Ford Coppola",
    "year": 1972,
    "genres": ["Crime", "Drama"]
}'

And finally, your term query will work on the title.raw sub-field:

$ curl -s -XPOST "http://localhost:9200/movies/_search" -d'
{
    "query": {
        "term": {"title.raw": "The Godfather"}
    }
}'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM