Validate API

validate API允许用户验证一个可能复杂(expensive)的查询而不执行它。我们将使用以下测试数据来解释_validate:

PUT twitter/tweet/_bulk?refresh
{"index":{"_id":1}}
{"user" : "kimchy", "post_date" : "2009-11-15T14:12:12", "message" : "trying out Elasticsearch"}
{"index":{"_id":2}}
{"user" : "kimchi", "post_date" : "2009-11-15T14:12:13", "message" : "My username is similar to @kimchy!"}

当发送一个有效查询时:

GET twitter/_validate/query?q=user:foo

响应包含有效:true:

{"valid":true,"_shards":{"total":1,"successful":1,"failed":0}}

Request Parameters

当执行查询使用查询参数q时,传递的查询是使用Lucene查询解析器的查询字符串。还有其他可以传递的参数:

查询也可以在请求主体中发送:

GET twitter/tweet/_validate/query
{
  "query" : {
    "bool" : {
      "must" : {
        "query_string" : {
          "query" : "*:*"
        }
      },
      "filter" : {
        "term" : { "user" : "kimchy" }
      }
    }
  }
}

注意

在正文中发送的查询必须嵌套在查询键中,与Search API相同。

如果查询无效,则返回信息中 valid将为 false。在这里,查询无效,因为Elasticsearch知道post_date字段应该是动态映射的日期,foo无法正确解析为日期:

GET twitter/tweet/_validate/query?q=post_date:foo

{"valid":false,"_shards":{"total":1,"successful":1,"failed":0}}

可以指定explain参数以获取有关查询失败原因的更详细信息:

GET twitter/tweet/_validate/query?q=post_date:foo&explain=true

响应是:

{
  "valid" : false,
  "_shards" : {
    "total" : 1,
    "successful" : 1,
    "failed" : 0
  },
  "explanations" : [ {
    "index" : "twitter",
    "valid" : false,
    "error" : "twitter/IAEc2nIXSSunQA_suI0MLw] QueryShardException[failed to create query:...failed to parse date field [foo]"
  } ]
}

当查询有效时,explanations默认为该查询的字符串表示形式。 将rewrite设置为true时,explanations将更详细地显示将要执行的实际Lucene查询。

模糊查询(Fuzzy Queries):

GET twitter/tweet/_validate/query?rewrite=true
{
  "query": {
    "match": {
      "user": {
        "query": "kimchy",
        "fuzziness": "auto"
      }
    }
  }
}

响应:

{
   "valid": true,
   "_shards": {
      "total": 1,
      "successful": 1,
      "failed": 0
   },
   "explanations": [
      {
         "index": "twitter",
         "valid": true,
         "explanation": "+user:kimchy +user:kimchi^0.75 #(ConstantScore(_type:tweet))^0.0"
      }
   ]
}

相似度查询(More Like This):

GET twitter/tweet/_validate/query?rewrite=true
{
  "query": {
    "more_like_this": {
      "like": {
        "_id": "2"
      },
      "boost_terms": 1
    }
  }
}

响应:

{
   "valid": true,
   "_shards": {
      "total": 1,
      "successful": 1,
      "failed": 0
   },
   "explanations": [
      {
         "index": "twitter",
         "valid": true,
         "explanation": "((user:terminator^3.71334 plot:future^2.763601 plot:human^2.8415773 plot:sarah^3.4193945 plot:kyle^3.8244398 plot:cyborg^3.9177752 plot:connor^4.040236 plot:reese^4.7133346 ... )~6) -ConstantScore(_uid:tweet#2)) #(ConstantScore(_type:tweet))^0.0"
      }
   ]
}

警告

请求只在单个分片上执行,这是随机选择的。查询的详细解释可以取决于哪个分片被命中,并且因此可以从一个请求到另一个请求而变化。

Last updated