Query DSL结合springboot使用
Query DSL
Elasticsearch 提供了基于 JSON 的完整 Query DSL(Domain Specific Language)来定义查询。
因Query DSL是利用Rest API传递JSON格式的请求体(RequestBody)数据与ES进行交互,所以我们在使用springboot的时候也可以很方便的进行集成,本文主要讲述的就是使用springboot实现各类DSL的语法查询。
Elasticsearch 官网地址
数据准备
新增名为(dsl_index)的索引,并插入部分数据,本文使用springboot变更Elasticsearch数据都是通过RestHighLevelClient来操作的
索引(dsl_index)结构:
GET dsl_index/_mappings
{
"dsl_index" : {
"mappings" : {
"properties" : {
"age" : {
"type" : "long"
},
"description" : {
"type" : "text",
"fields" : {
"keyword" : {
"type" : "keyword",
"ignore_above" : 256
}
}
},
"name" : {
"type" : "text",
"analyzer" : "ik_max_word",
"search_analyzer" : "ik_smart"
}
}
}
}
}
索引(dsl_index)数据:
POST /dsl_index/_bulk
{
"index":{
"_id":1}}
{
"name":"张三","age":11,"description":"南京市 羽毛球爱好者"}
{
"index":{
"_id":2}}
{
"name":"王五","age":15,"description":"北京市 篮球两年半"}
{
"index":{
"_id":3}}
{
"name":"李四","age":18,"description":"山东省 游泳健身"}
{
"index":{
"_id":4}}
{
"name":"富贵","age":22,"description":"天津市 游泳打球"}
{
"index":{
"_id":5}}
{
"name":"来福","age":8,"description":"安徽合肥 职业代练"}
{
"index":{
"_id":6}}
{
"name":"憨憨","age":27,"description":"北京市 健身打球"}
{
"index":{
"_id":7}}
{
"name":"小七","age":31,"description":"北京市 游泳"}
match_all
match_all会查询指定索引下的所有文档,但是默认只会返回10条数据。原因是:_search查询默认采用的是分页查询,from=0;size=10 如果想显示更多数据,指定size数量
DSL: 查询当前索引下所有数据(默认前十条)
GET dsl_index/_search
{
"query": {
"match_all": {
}
}
}
返回数据如下:
{
"took" : 0,
"timed_out" : false,
"_shards" : {
"total" : 1,
"successful" : 1,
"skipped" : 0,
"failed" : 0
},
"hits" : {
"total" : {
"value" : 7,
"relation" : "eq"
},
"max_score" : 1.0,
"hits" : [
{
"_index" : "dsl_index",
"_type" : "_doc",
"_id" : "1",
"_score" : 1.0,
"_source" : {
"name" : "张三",
"age" : 11,
"description" : "南京市 羽毛球爱好者"
}
},
{
"_index" : "dsl_index",
"_type" : "_doc",
"_id" : "2",
"_score" : 1.0,
"_source" : {
"name" : "王五",
"age" : 15,
"description" : "北京市 篮球两年半"
}
},
{
"_index" : "dsl_index",
"_type" : "_doc",
"_id" : "3",
"_score" : 1.0,
"_source" : {
"name" : "李四",
"age" : 18,
"description" : "山东省 游泳健身"
}
},
{
"_index" : "dsl_index",
"_type" : "_doc",
"_id" : "4",
"_score" : 1.0,
"_source" : {
"name" : "富贵",
"age" : 22,
"description" : "天津市 游泳打球"
}
},
{
"_index" : "dsl_index",
"_type" : "_doc",
"_id" : "5",
"_score" : 1.0,
"_source" : {
"name" : "来福",
"age" : 8,
"description" : "安徽合肥 职业代练"
}
},
{
"_index" : "dsl_index",
"_type" : "_doc",
"_id" : "6",
"_score" : 1.0,
"_source" : {
"name" : "憨憨",
"age" : 27,
"description" : "北京市 健身打球"
}
},
{
"_index" : "dsl_index",
"_type" : "_doc",
"_id" : "7",
"_score" : 1.0,
"_source" : {
"name" : "小七",
"age" : 31,
"description" : "北京市 游泳"
}
}
]
}
}
sprongboot实现:
代码:
private static final String INDEX_NAME = "dsl_index"; -- 以下统一使用该索引
@Resource
private RestHighLevelClient client; -- 以下统一使用该client
@RequestMapping(value =