Elasticsearch DSL 查询

DSL 是 Domain Specific Language(特定领域语言)的缩写。

Elasticsearch 提供了功能丰富且灵活的查询语言,即 DSL 查询。你可以用它构建出更加复杂、功能更加强大的查询语句。

先来一个简单的例子,比如,我们可以这样查询 first_name 字段包含 John 的用户。

GET /alibaba/user/_search
{
    "query" : {
        "match" : {
            "first_name" : "John"
        }
    }
}

它会返回和上一节中的查询字符串搜索相同的结果。只不过这里我们不再使用查询字符串作为请求参数,而是使用 JSON 格式的请求体。

bool 联合查询

逻辑与(AND)

下面,我们来进行一个稍微复杂点的查询。比如,查询姓氏包含 Smith 且年龄大于 30 岁的用户。

GET /alibaba/user/_search
{
    "query" : {
        "bool" : {
            "filter" : {
                "range" : {
                    "info.age" : { "gt" : 30 }
                }
            },
            "must" : [{
                "match" : {
                    "last_name" : "smith"
                }
            }]
        }
    }
}

返回结果:

{
  "took": 4,
  "timed_out": false,
  "_shards": {
    "total": 5,
    "successful": 5,
    "failed": 0
  },
  "hits": {
    "total": 1,
    "max_score": 0.2876821,
    "hits": [
      {
        "_index": "alibaba",
        "_type": "user",
        "_id": "3",
        "_score": 0.2876821,
        "_source": {
          "email": "[email protected]",
          "first_name": "John3",
          "last_name": "Smith",
          "full_name": "John3 Smith",
          "info": {
            "age": 35,
            "interests": [
              "sports",
              "musics"
            ],
            "address": "guangdong shenzhen longhua"
          },
          "created_at": "2019-06-08 09:40:10"
        }
      }
    ]
  }
}

查询 last_name 包含 Smith,且 full_name 包含 John 的用户。

GET /alibaba/user/_search
{
  "query": {
    "bool": {
      "must": [
        { "match": { "last_name": "Smith" } },
        { "match": { "full_name": "John" } }
      ]
    }
  }
}

返回结果:

{
  "took": 4,
  "timed_out": false,
  "_shards": {
    "total": 5,
    "successful": 5,
    "failed": 0
  },
  "hits": {
    "total": 1,
    "max_score": 0.5457982,
    "hits": [
      {
        "_index": "alibaba",
        "_type": "user",
        "_id": "1",
        "_score": 0.5457982,
        "_source": {
          "email": "[email protected]",
          "first_name": "John",
          "last_name": "Smith",
          "
  • 1
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值