ElasticSearch搜索term和terms的区别

今天同事使用ES查询印地语的文章。发现查询报错,查询语句和错误信息如下:

查询语句:
{
    "query":{
        "bool":{
            "must":[
                {
                    "range":{
                        "update_time":{
                            "gt":"1488556800000"
                        }
                    }
                },
                {
                    "terms":{
                        "lang":1
                    }
                },
                {
                    "terms":{
                        "domain":[
                            "dailymasala.co",
                            "goldenmob.com"
                        ]
                    }
                },
                {
                    "prefix":{
                        "user_id":"errVideo_setInterval_"
                    }
                }
            ]
        }
    },
    "from":0,
    "size":10
}


错误信息:
{
    "error":{
        "root_cause":[
            {
                "type":"parsing_exception",
                "reason":"[terms] query does not support [lang]",
                "line":1,
                "col":93
            }
        ],
        "type":"parsing_exception",
        "reason":"[terms] query does not support [lang]",
        "line":1,
        "col":93
    },
    "status":400
}

其实这么看上去好像并没有什么问题,但是就是查询不成功。

问题出在查询lang这个字段上。

在查询的字段只有一个值的时候,应该使用term而不是terms,在查询字段包含多个的时候才使用terms(类似于sql中的in、or),使用terms语法,JSON中必须包含数组。

正确的写法如下:

第一种(单个值,term):
{
    "query":{
        "bool":{
            "must":[
                {
                    "range":{
                        "update_time":{
                            "gt":"1488556800000"
                        }
                    }
                },
                {
                    "term":{
                        "lang":1
                    }
                },
                {
                    "terms":{
                        "domain":[
                            "dailymasala.co",
                            "goldenmob.com"
                        ]
                    }
                },
                {
                    "prefix":{
                        "user_id":"errVideo_setInterval_"
                    }
                }
            ]
        }
    },
    "from":0,
    "size":10
}



第二种(数组形式,terms):
{
  "query": {
    "bool": {
      "must": [
        {
          "range": {
            "update_time": {
              "gt": "1488556800000"
            }
          }
        },
        {
          "terms": {
            "lang": [1]
          }
        },
        {
          "terms": {
            "domain": [
              "dailymasala.co",
              "goldenmob.com"
            ]
          }
        },
        {
          "prefix": {
            "user_id": "errVideo_setInterval_"
          }
        }
      ]
    }
  },
  "from": 0,
  "size": 10
}

 

posted @ 2017-03-08 20:49  0xcafedaddy  阅读(13749)  评论(0编辑  收藏  举报