分布式系列教程(33) -ElasticSearch DSL语言查询与过滤

ES中的查询请求有两种方式,一种是简易版的查询,另外一种是使用JSON完整的请求体,叫做结构化查询(DSL)。由于DSL查询更为直观也更为简易,所以大都使用这种方式。

DSL查询是POST过去一个JSON,由于POST的请求是JSON格式的,所以存在很多灵活性,也有很多形式。

下面来举些例子:

1. 根据名称精准查询姓名

GET user_dao/user/_search
{
  "query": {
    "term": {
      "name": "father"
    }
    
  }
}

返回内容:
在这里插入图片描述
注意:term是代表完全匹配,即不进行分词器分析,文档中必须包含整个搜索的词汇。


2. 根据名称模糊查询姓名

GET /user_dao/user_table/_search
{
  "from": 0,
  "size": 3, 
  "query": {
    "match": {
        "name": "grand"
      }
  }
}

返回结果:

  • name为grand的所有文档。

注意:

  • 「Match」相当于模糊匹配,只包含其中一部分关键词就行。
  • 「Match」会根据该字段的分词器,进行分词查询,而「Term」查询不会对字段进行分词查询,会采用精确匹配。

3. 使用filter过滤年龄

GET /user_dao/user_table/_search
{
	"query": {
		"bool": {
			"must": [{
				"match_all": {}
			}],
			"filter": {
				"range": {
					"age": {
						"gt": 20,
						"lte": 60
					}
				}

			}

		}

	},
	"from": 0,
	"size": 10,
	"_source": ["name", "age"]

}

返回内容:

{
  "took": 17,
  "timed_out": false,
  "_shards": {
    "total": 5,
    "successful": 5,
    "skipped": 0,
    "failed": 0
  },
  "hits": {
    "total": 4,
    "max_score": 1,
    "hits": [
      {
        "_index": "user_dao",
        "_type": "user_table",
        "_id": "5",
        "_score": 1,
        "_source": {
          "name": "grandmother",
          "age": 58
        }
      },
      {
        "_index": "user_dao",
        "_type": "user_table",
        "_id": "2",
        "_score": 1,
        "_source": {
          "name": "father",
          "age": 26
        }
      },
      {
        "_index": "user_dao",
        "_type": "user_table",
        "_id": "4",
        "_score": 1,
        "_source": {
          "name": "grandfather",
          "age": 60
        }
      },
      {
        "_index": "user_dao",
        "_type": "user_table",
        "_id": "3",
        "_score": 1,
        "_source": {
          "name": "mother",
          "age": 24
        }
      }
    ]
  }
}
  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值