当前位置: 动力学知识库 > 问答 > 编程问答 >

elasticsearch - query must match 2 fields exactly, don't analyze

问题描述:

I tried a few different ways of doing a simple get request, filtering on two different attributes, example:

"query": {

"filtered": {

"filter": {

"bool": {

"must": [

{

"term": {

"email": "[email protected]"

}

},

{

"term": {

"password": "bb3810356e9b60cf6..."

}

}

]

}

},

"query": {

"match_all": []

}

}

}

The problem is that I get nothing back in return. As I understand it, this is because ElasticSearch analyzes the email field, making the query fail. So if I however would use the term erik.landvall instead of the complete email address, it will match the document - which confirms that's what's going on.

I can define the attribute as type:string and index:not_analyzed when I create the index. But what if I wanna be able to search on the email attribute in a different context? So there should, to my mind, be a way to specify that I wanna filter on the actual value of the attribute in a query. I can however not find how such a query would look.

Is it possible to force Elasticsearch to use "not_analyze" when querying? If so, then how?

网友答案:

You can use scripting for this purpose. You would have to directly access the JSON you have stored with _source. Try following query

{
  "query": {
    "bool": {
      "filter": {
        "script": {
          "script": {
                "inline" : "_source.email==param1 && _source.password==param2",
                "params" : {
                    "param1" : "[email protected]",
                    "param2" : "bb3810356e9b60cf6"
                }
            }
        }
      }
    }
  }
}

You would need to enable dynamic scripting. Add script.inline: on to your yml file and restart the node.

If this kind of query is fairly regular then It would be much better to reindex the data as others have suggested in the comments.

网友答案:

Its not possible to turn on/off analyzed or not, the way to do it to "transform" your field to analysis you need by using fields.

curl -XPUT 'localhost:9200/my_index?pretty' -d'
{
  "mappings": {
    "my_type": {
      "properties": {
        "city": {
          "type": "string",
          "fields": {
            "raw": { 
              "type":  "string",
              "index": "not_analyzed"
            }
          }
        }
      }
    }
  }
}'
curl -XPUT 'localhost:9200/my_index/my_type/1?pretty' -d'
{
  "city": "New York"
}'
curl -XPUT 'localhost:9200/my_index/my_type/2?pretty' -d'
{
  "city": "York"
}'
curl -XGET 'localhost:9200/my_index/_search?pretty' -d'
{
  "query": {
    "match": {
      "city": "york" 
    }
  },
  "sort": {
    "city.raw": "asc" 
  },
  "aggs": {
    "Cities": {
      "terms": {
        "field": "city.raw" 
      }
    }
  }

}'

分享给朋友:
您可能感兴趣的文章:
随机阅读: