elasticsearch 复合查询

15 篇文章 0 订阅

                                                     ElasticSearch 复合查询

 

1.pom依赖

<!-- https://mvnrepository.com/artifact/org.elasticsearch.client/transport -->
        <dependency>
            <groupId>org.elasticsearch.client</groupId>
            <artifactId>transport</artifactId>
        </dependency>

        <!-- elasticsearch -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-elasticsearch</artifactId>
        </dependency>

        <!-- https://mvnrepository.com/artifact/org.elasticsearch/elasticsearch -->
        <dependency>
            <groupId>org.elasticsearch</groupId>
            <artifactId>elasticsearch</artifactId>
        </dependency>

2.配置

spring:
    data:
        elasticsearch:
            cluster-name: senseguard-logging
            cluster-nodes: 172.20.25.89:31191
            properties:
                client.transport.sniff: true

3.配置类 config

@Configuration
public class EsConfig {
    private TransportClient client;

    @Value("${spring.data.elasticsearch.cluster-name}")
    private String clusterName;

    @Value("${spring.data.elasticsearch.cluster-nodes}")
    private String clusterAddress;

    @Bean
    public TransportClient esclient() {
        try {
            Settings settings = Settings.builder().put("cluster.name", clusterName).build();

            client = new PreBuiltTransportClient(settings);
            String[] nodes = clusterAddress.split(",");
            for (String node : nodes) {
                if (node.length() > 0) {
                    String[] hostPort = node.split(":");
                    this.client.addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName(hostPort[0]),
                            Integer.parseInt(hostPort[1])));
                }
            }
        } catch (Exception e) {
        }
        return client;
    }

}

4. TransportClient 复杂、混合、排序 查询

/**
     * ES嵌套查询最外层数据转换成导出数据.
     * 
     * @param source
     * @param export
     * @throws ParseException
     * @throws ExecutionException
     * @throws InterruptedException
     */
    public List<DetectHistory> search(ImdaRequest imda)
            throws ParseException, InterruptedException, ExecutionException {
        List<DetectHistory> detectHistorieList = new LinkedList<>();
        try {
            // 创建builder
            BoolQueryBuilder builder = QueryBuilders.boolQuery();

            // builder下有must、should以及mustNot 相当于sql中的and、or以及not
            Long startTime = imda.getCaptureTimeStart();
            Long endTime = imda.getCaptureTimeEnd();

            // 抓拍时间筛选
            builder.must(QueryBuilders.rangeQuery("capturedTime").gte(startTime).lte(endTime));

            // 摄像头 ID
            if (imda.getCameraIds().size() > 0 && imda.getCameraIds().get(0) > 0) {
                builder.must(QueryBuilders.termsQuery("camera.id", imda.getCameraIds()));
            }
            // 人像库
            if (imda.getFaceDatabase().size() > 0 && imda.getFaceDatabase().get(0) > 0) {
                builder.must(QueryBuilders.termsQuery("targetLibrary.id", imda.getFaceDatabase()));
            }

            // 确认时间筛
            RangeQueryBuilder confirmRangeQueryBuilder = QueryBuilders.rangeQuery("acknowledge.operationTime");
            // 挨个设置查询条件,没有就不加,如果是字符串类型的,要加keyword后缀
            // 确认状态
            if (!StringUtils.isEmpty(imda.getConfirmStatus()) && Integer.parseInt(imda.getConfirmStatus()) > 0) {
                if (!StringUtils.isEmpty(imda.getConfirmTimeStart())) {
                    Long confirmStart = imda.getConfirmTimeStart();
                    confirmRangeQueryBuilder.gte(confirmStart);
                }
                if (!StringUtils.isEmpty(imda.getConfirmTimeEnd())) {
                    Long confirmEnd = imda.getConfirmTimeEnd();
                    confirmRangeQueryBuilder.lte(confirmEnd);
                }
                builder.must(confirmRangeQueryBuilder);
                builder.must(QueryBuilders.matchPhraseQuery("acknowledge.status.keyword", imda.getConfirmStatus()));
            }

            BoolQueryBuilder keywordQueryShould = QueryBuilders.boolQuery();
            String keyword = imda.getName();
            // 搜索关键字
            if (!StringUtils.isEmpty(keyword)) {
                String keywordLower = "*" + keyword.toLowerCase() + "*";
                keyword = "*" + keyword + "*";
                // 名字
                keywordQueryShould.should(QueryBuilders.wildcardQuery("target.lowerName.keyword", keywordLower));
                // 部门
                keywordQueryShould.should(QueryBuilders.wildcardQuery("target.lowerDept.keyword", keywordLower));
                //公司
                keywordQueryShould.should(QueryBuilders.wildcardQuery("target.lowerCompany.keyword", keywordLower));
                // camera name
                keywordQueryShould.should(QueryBuilders.wildcardQuery("camera.name.keyword", keyword));
                // keeper-group 名称
                keywordQueryShould.should(QueryBuilders.wildcardQuery("camera.groupName.keyword", keyword));
                // 人像库名称
                keywordQueryShould.should(QueryBuilders.wildcardQuery("targetLibrary.name.keyword", keyword));
                // 员工编号
                keywordQueryShould.should(QueryBuilders.wildcardQuery("target.cardId.keyword", keyword));
                // 单位名称
                keywordQueryShould.should(QueryBuilders.wildcardQuery("target.company.keyword", keyword));
                // 国籍
                keywordQueryShould.should(QueryBuilders.wildcardQuery("target.nationality.keyword", keyword));
                // 确认人的名称
                keywordQueryShould.should(QueryBuilders.wildcardQuery("acknowledge.realname.keyword", keyword));
                // 确认人的id
//                keywordQueryShould.should(QueryBuilders.wildcardQuery("acknowledge.userId.keyword", keyword));
            }

            builder.must(keywordQueryShould);

            // 比对结果
            if (!StringUtils.isEmpty(imda.getComparedType()) && imda.getComparedType().size() > 0) {
                List<String> types = imda.getComparedType();

                BoolQueryBuilder comparedBuilder = null;
                BoolQueryBuilder comparedShould = QueryBuilders.boolQuery();

                for (String type : types) {
                    switch (type) {
                    case "NORMAL":
                        comparedBuilder = QueryBuilders.boolQuery();
                        comparedBuilder.must(QueryBuilders.matchQuery("detectStatus.keyword",
                                ComparedTypeEnum.NORMAL.getDetectStatus()));
                        comparedBuilder
                                .must(QueryBuilders.matchQuery("status.keyword", ComparedTypeEnum.NORMAL.getStatus()));
                        comparedShould.should(comparedBuilder);
                        break;
                    case "ABNORMAL":
                        comparedBuilder = QueryBuilders.boolQuery();
                        comparedBuilder.must(QueryBuilders.matchQuery("detectStatus.keyword",
                                ComparedTypeEnum.ABNORMAL.getDetectStatus()));
                        comparedBuilder.must(
                                QueryBuilders.matchQuery("status.keyword", ComparedTypeEnum.ABNORMAL.getStatus()));
                        comparedShould.should(comparedBuilder);
                        break;
                    case "STRANGER":
                        comparedBuilder = QueryBuilders.boolQuery();
                        comparedBuilder.must(QueryBuilders.matchQuery("detectStatus.keyword",
                                ComparedTypeEnum.STRANGER.getDetectStatus()));
                        comparedBuilder.must(
                                QueryBuilders.matchQuery("status.keyword", ComparedTypeEnum.STRANGER.getStatus()));
                        comparedShould.should(comparedBuilder);
                        break;
                    }
                }

                builder.must(comparedShould);
            }

            SortBuilder sortBuilder = SortBuilders.fieldSort("capturedTime").order(SortOrder.DESC);

            int size = 0;
            int from = 0;

            if (imda.getFrom() == imda.getTo()) {
                size = 1;
            } else {
                size = imda.getTo() - imda.getFrom() + 1;
            }
            if (imda.getFrom() > SFUUMSConstant.ONE) {
                from = imda.getFrom() - 1;
            }

            SearchResponse searchResponse = client.prepareSearch("tdhistory").setTypes("tdhistory")
                    .setSearchType(SearchType.DFS_QUERY_THEN_FETCH).setQuery(builder).addSort(sortBuilder).setFrom(from)
                    .setSize(size).execute().get();

            SearchHits searchHits = searchResponse.getHits();

            logger.info("td Conditional query total :" + searchHits.getTotalHits());

            DetectHistory detectHistory = null;

            for (SearchHit searchHit : searchHits) {
                detectHistory = JSON.parseObject(searchHit.getSourceAsString(), DetectHistory.class);  

                detectHistorieList.add(detectHistory);
            }
            return detectHistorieList;
        } catch (Exception e) {
            // TODO: handle exception
            e.printStackTrace();
        }

        return detectHistorieList;
    }
 

5.查询完毕,输出结果

总结:

1.查询字段名要和存的字段一样,不然查询不到结果

2.String 类型的字段后面要加keyword 

3.String 查询用 QueryStringQueryBuilder,时间段查询用 RangeQueryBuilder

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值