欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

elk之查询(单个或多个)type所有数据,条件查询,分页查询,排序

程序员文章站 2024-03-06 09:57:37
...

java连接es:

1、接口:

    /**
     * 查询(单个或多个)type所有数据,条件查询,分页查询,排序
     * @param client
     * @param indexName
     * @param typeName
     */
    public void searchAllStudent(TransportClient client, String indexName, String typeName);
2.实现类:(注释!!)
@Override
    public void searchAllStudent(TransportClient client, String indexName, String typeName) {

//        多索引,多type查询
//        SearchResponse searchResponse = client.prepareSearch("shb01","shb02").setTypes("stu","tea")

        //创建SearchResponse对象
        SearchResponse searchResponse = client.prepareSearch(indexName)
                .setTypes(typeName)
                //查询所有
                .setQuery(QueryBuilders.matchAllQuery())
                .setSearchType(SearchType.QUERY_THEN_FETCH)
                //根据夏文杰查询name,数据库like,指定查询条件,这里不支持通配符 * ?
                .setQuery(QueryBuilders.matchQuery("name", "夏文杰"))
                //等价于SQL语句,支持一个值同时匹配多个字段,就是,where name=2 or age=2
                .setQuery(QueryBuilders.multiMatchQuery("2", "name", "age"))
                //根据条件查询,支持通配符大于等于0小于等于19
                .setQuery(QueryBuilders.queryStringQuery("name:夏文杰 AND age:[0 TO 19]"))
                //查询时不分词
                .setQuery(QueryBuilders.termQuery("name", "夏文杰4"))
                //分页
                .setFrom(0).setSize(10)
                //排序
                .addSort("age", SortOrder.DESC)
                .setExplain(true)//按照查询数据的匹配度返回数据
                .get();
        SearchHits hits = searchResponse.getHits();
        long total = hits.getTotalHits();
        System.out.println(total);
        //获取满足条件数据的详细内容
        SearchHit[] searchHits = hits.hits();
        for (SearchHit s : searchHits) {
            System.out.println(s.getSourceAsString());
        }
    }

3.测试类:

  searchService.searchAllStudent(ConEsUtil.creatConEs(),"school1","student");