elasticsearch 7.6 获取查询结果集count

分页插件需要{count}这个参数,类似MYSQL中的select count(*) from user where userType=1,获取结果集的count数量。

JAVA有两种方式可以获得

1、将SearchSourceBuilder的“size”参数设置为0,获取结果集的“hits.total.value”得到count

2、查询语句不变,使用RestHighLevelClient.count()方法获取,创建CountRequest传入QueryBuilder(与SearchSourceBuilder使用相同)

代码:

public class FNewsImpl implements FNewsService {
    @Autowired
    ElasticService elasticService;
/**
     * 查找标题和内容
     * @param pageRequest
     * @return
     */
    @Override
    public ReturnESList getNewsES(PageRequest pageRequest)
    {
        // 创建BoolQueryBuilder
        BoolQueryBuilder boolQueryBuilder = new BoolQueryBuilder();
        // 设置条件
        MatchPhraseQueryBuilder matchPhraseQueryBuilder = QueryBuilders
                .matchPhraseQuery("ftitle", pageRequest.getKeywords());
        MatchPhraseQueryBuilder matchPhraseQueryBuilder2 = QueryBuilders
                .matchPhraseQuery("fbastan", pageRequest.getKeywords());
        // 子查询“或”关系
        BoolQueryBuilder childBoolQueryBuilder = new BoolQueryBuilder()
                .should(matchPhraseQueryBuilder)
                .should(matchPhraseQueryBuilder2);
        boolQueryBuilder.must(childBoolQueryBuilder);
        // 创建SearchSourceBuilder
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
        // 查询条件生成DSL语句
        searchSourceBuilder.query(boolQueryBuilder);
        // 从多少
        searchSourceBuilder.from(pageRequest.getPageNum());
        // 查多少条数据,如果设置“0”返回count数量
        searchSourceBuilder.size(pageRequest.getPageSize());
        // 排序规则
        searchSourceBuilder.sort("fcreatetime", SortOrder.DESC);
        // 设置超时
        TimeValue t=new TimeValue(3000);
        searchSourceBuilder.timeout(t);
        Class<?> clazz = ElasticUtil.getClazz(FquestionES.class.getName());
        //查询结果集
        List<?> data = elasticService.search(EsEnum.ES_INDEX,searchSourceBuilder,clazz);
        //查询count
        long count=elasticService.count(EsEnum.ES_INDEX,boolQueryBuilder);
        ReturnESList list=new ReturnESList();
        list.setSize(count);
        list.setData((List<FquestionES>) data);
        return list;
    }
}
@Service
public class ElasticService {
    @Autowired
    RestHighLevelClient restHighLevelClient;
    
/**
     * 根据条件查询
     * @param idxName index
     * @param builder   查询参数
     * @param c 结果类对象
     */
    public <T> List<T> search(String idxName, SearchSourceBuilder builder, Class<T> c) {
        SearchRequest request = new SearchRequest(idxName);
        request.source(builder);
        try {
            SearchResponse response = restHighLevelClient.search(request, RequestOptions.DEFAULT);
            SearchHit[] hits = response.getHits().getHits();
            List<T> res = new ArrayList<>(hits.length);
            for (SearchHit hit : hits) {
                res.add(JSON.parseObject(hit.getSourceAsString(), c));
            }
            return res;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 查询条件下共有多少条
     * @param idxName index
     * @param builder   查询参数
     */
    public long count(String idxName, QueryBuilder builder) {
        CountRequest countRequest=new CountRequest(idxName);
        countRequest.query(builder);
        try {
            CountResponse response=restHighLevelClient.count(countRequest,RequestOptions.DEFAULT);
            long length = response.getCount();
            return length;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return 0;
    }
}

 

  • 4
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
以下是使用 Spring Boot 操作 Elasticsearch 7.6 进行 SQL 查询的示例代码: 1. 添加 ElasticsearchElasticsearch SQL 依赖库到 pom.xml 文件中: ```xml <dependency> <groupId>org.elasticsearch.client</groupId> <artifactId>elasticsearch-rest-client</artifactId> <version>7.6.0</version> </dependency> <dependency> <groupId>org.elasticsearch.plugin</groupId> <artifactId>x-pack-sql-jdbc</artifactId> <version>7.6.0</version> </dependency> ``` 2. 配置 Elasticsearch client: ```java @Configuration public class ElasticsearchConfig { @Value("${elasticsearch.host}") private String host; @Value("${elasticsearch.port}") private int port; @Bean public RestHighLevelClient client() { RestClientBuilder builder = RestClient.builder(new HttpHost(host, port, "http")); return new RestHighLevelClient(builder); } } ``` 3. 编写 SQL 查询代码: ```java @Service public class ElasticsearchService { @Autowired private RestHighLevelClient client; public void sqlQuery() throws IOException, SQLException { String sql = "SELECT * FROM my_index WHERE age > 30"; PreparedStatement statement = client.sql().prepareStatement(sql); ResultSet resultSet = statement.executeQuery(); while (resultSet.next()) { System.out.println(resultSet.getString("name") + " - " + resultSet.getInt("age")); } } } ``` 在上面的代码中,我们使用 `RestHighLevelClient` 对象调用 `sql()` 方法生成 `PreparedStatement` 对象,然后执行 SQL 查询并遍历结果。 4. 在 application.properties 文件中配置 Elasticsearch 地址和端口号: ``` elasticsearch.host=localhost elasticsearch.port=9200 ``` 这样,我们就可以使用 Spring Boot 操作 Elasticsearch 7.6 进行 SQL 查询了。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值