ElasticSearch中嵌套结构使用

1.需求

需求看板查看全国各省的城市,当选中江西省时,可以点进去查看江西省的各大城市;

2.ElasticSearch嵌套数据存储结构

  这个情况呢,可以存两个index,形成一对多的关系来查询;那这里说另一种结构,嵌套结构;
  官网介绍:Nested datatype
  建表语句如下,citys_list就是一个嵌套结构,你可以认为citys_list是一个列表,列表里面的每个元素是一个结构体,结构体里面有两个元素city_id和city_name;

PUT /map_area
{
    "settings": 
    {
        "number_of_replicas": 2,
        "number_of_shards": 1
    },
    "mappings": 
    {
        "properties":
        {
            "province_id":
            {
                "type":"long"
            },
            "province_name":
            {
                "type":"keyword"
            },
            "citys_list":
            {
              "type": "nested",
              "properties": 
              {
                  "city_id":
                 {
                    "type":"long"
                 },
                 "city_name":
                 {
                    "type":"keyword"
                 }
              }
            }
        }
    }
}

3.ElasticSearch嵌套数据写入

POST /map_area/_doc
{
  "province_id":360000,
  "province_name":"江西省",
  "citys_list":[
                   {
                     "city_id":360100
                     ,"city_name":"南昌市"
                   },
                   {
                     "city_id":360700
                     ,"city_name":"赣州市"
                   }
              ]
}

4.ElasticSearch嵌套查询

  普通查询:查询嵌套内的field时,也需要需要加入关键字nested,如查询有赣州市的es文档;

GET /map_area/_search
{
  "query": {
    "nested": {
      "path": "citys_list",
      "query": {
        "match": {
          "citys_list.city_name":"赣州市"
        }
      }
    }
  }
}

# 结果
{
  "took" : 78,
  "timed_out" : false,
  "_shards" : {
    "total" : 1,
    "successful" : 1,
    "skipped" : 0,
    "failed" : 0
  },
  "hits" : {
    "total" : {
      "value" : 1,
      "relation" : "eq"
    },
    "max_score" : 0.6931471,
    "hits" : [
      {
        "_index" : "map_area",
        "_type" : "_doc",
        "_id" : "-EERFXgBVEqNSrz8HG4V",
        "_score" : 0.6931471,
        "_source" : {
          "province_id" : 360000,
          "province_name" : "江西省",
          "citys_list" : [
            {
              "city_id" : 360100,
              "city_name" : "南昌市"
            },
            {
              "city_id" : 360700,
              "city_name" : "赣州市"
            }
          ]
        }
      }
    ]
  }
}

  聚合查询

GET /map_area/_search
{
  "size" : 0,
  "aggs": {
    "comments": {
      "nested": { 
        "path": "citys_list"
      },
      "aggs": {
        "age_group": {
          "extended_stats": { 
            "field":    "citys_list.city_id"
          }
        }
      }
    }
  }
}

# 结果
{
  "took" : 145,
  "timed_out" : false,
  "_shards" : {
    "total" : 1,
    "successful" : 1,
    "skipped" : 0,
    "failed" : 0
  },
  "hits" : {
    "total" : {
      "value" : 1,
      "relation" : "eq"
    },
    "max_score" : null,
    "hits" : [ ]
  },
  "aggregations" : {
    "comments" : {
      "doc_count" : 2,
      "age_group" : {
        "count" : 2,
        "min" : 360100.0,
        "max" : 360700.0,
        "avg" : 360400.0,
        "sum" : 720800.0,
        "sum_of_squares" : 2.597765E11,
        "variance" : 90000.0,
        "std_deviation" : 300.0,
        "std_deviation_bounds" : {
          "upper" : 361000.0,
          "lower" : 359800.0
        }
      }
    }
  }
}

5.ElasticSearch嵌套Java API操作

  插入数据

@Service
@Log4j2
public class EsServiceImpl<T> implements EsService<T> {
 
    @Resource
    private RestHighLevelClient restHighLevelClient;
 
    //此处是批量存储
    @Override
    public BulkResponse save(List<T> list,XContentBuilder mapping,String index,String type) {
        BulkResponse bulkResponse = null ;
        if (list != null && list.size() != 0) {
            try {
                EsServiceImpl.log.info("......start to save......");
                //这里就是用的判断index是否存在的方法
                if(isNotExists(index,type)){
                    createIndex(mapping,index,type);
                }
 
                BulkRequest bulkRequest = new BulkRequest();
 
                for (T tt : list) {
                    bulkRequest.add((new IndexRequest(index, type, getESId(tt))).source(JSON.toJSONString(tt), XContentType.JSON));
                }
                bulkResponse = this.restHighLevelClient.bulk(bulkRequest, RequestOptions.DEFAULT);
                BulkItemResponse[] responses = bulkResponse.getItems();
                log.info("... insert success {} ",responses.length);
                Arrays.stream(responses).forEach(response->{
                    if(StringUtils.isEmpty(response.getId())){
                        log.info("... response id is empty ...");
                    }
                    if(response.getFailure()!=null){
                        log.info("... response failure ...");
                    }
                });
                if(bulkResponse.hasFailures()){
                    log.info("... save failure {} ..." , bulkResponse.buildFailureMessage());
                }
            }catch (Exception e){
                log.error("... save failure ..." , e);
            }
        }
        return bulkResponse;
    }
 
}

  查询,以match查询为例;

NestedQueryBuilder nq = nestedQuery("citys_list",matchQuery("citys_list.city_id",label),ScoreMode.Total);
  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

╭⌒若隐_RowYet——大数据

谢谢小哥哥,小姐姐的巨款

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值