简体   繁体   中英

Elasticsearch terms with spaces

I have a list of users with their interests in ElasticSearch:

Here's the mapping I have:

      mappings: {
        users: {
          properties: {
            username: {
              type: 'text',
              analyzer: 'autocomplete',
              search_analyzer: 'autocomplete'
            },
            interests: {
              type: 'text'
            },
            locations: {
              type: 'text'
            },
            roles: {
              type: 'text'
            }
          }
        }
      },
      settings: {
        analysis: {
          analyzer: {
            autocomplete: {
              type: 'custom',
              tokenizer: 'autocomplete',
              filter: ['lowercase']
            }
          },
          tokenizer: {
            autocomplete: {
              type: 'edge_ngram',
              min_gram: 3,
              max_gram: 10,
              token_chars: [
                'letter', 'digit'
              ]
            }
          }
        }
      }

Here's an example document:

  {
   "_index": "users",
   "_type": "users",
   "_id": "4",
   "_score": 1.0,
   "_source": {
     "username": null,
     "interests": [
       "live events"
     ],
     "locations": [
       "abington",
       "connecticut"
     ],
     "roles": [

     ]
   }
 }

Now when I search for:

{
  terms: ["live events"]
}

I get no results. I checked and it turns out that if the term contains a space then this happens. My guess was that terms looks for exact matches, but I am unable to understand what's going on here.

You should use the term/terms query only for keyword datatype. In your case you are querying against a field with a text datatype ,as written in your mapping:

    interests: {
      type: 'text'
    }

In this case you have to use the match query, instead, so:

{
    "query": {
        "match" : {
            "interests" : "live events"
        }
    }
}

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