RestHighLevelClient查询ES

Posted Firm陈

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了RestHighLevelClient查询ES相关的知识,希望对你有一定的参考价值。

RestHighLevelClient查询ES中数据的API主要有:get、multiGet、search、multiSearch、searchScroll,每个方法还有异步查询的操作方法。下面我们就逐个看看这些API的应用。

链接ES构建客户端:

public class EsRestClient 
 
    private String IP;
    private int PORT;
    private String index;
    private String type;
    RestHighLevelClient client;
 
    @Before
    public void init() 
        this.IP = "192.168.5.166";
        this.PORT = 9200;
        this.index = "index3";
        this.type = "user1";
        client = new RestHighLevelClient(
                RestClient.builder(
                        new HttpHost(IP, PORT, "http")));
    
 

get方法查询:

public final GetResponse get(GetRequest getRequest, Header... headers) throws IOException 
        return (GetResponse)this.performRequestAndParseEntity(getRequest, Request::get, GetResponse::fromXContent, Collections.singleton(404), headers);
    

查询ES:

    @Test
    public void test1() throws IOException 
        GetRequest getRequest = new GetRequest(index);
        getRequest.id("1");
        String[] includes = new String[]"*", "birthday";
        String[] excludes = Strings.EMPTY_ARRAY;
        FetchSourceContext fetchSourceContext = new FetchSourceContext(true, includes, excludes);
        getRequest.fetchSourceContext(fetchSourceContext);
        GetResponse response = client.get(getRequest);
        System.out.println(response.getSource().keySet().toString());
    

输出结果:

get方法查询es接收的参数为GetRequest,我们先要构建GetRequest对象才可以对ES进行查询

public class GetRequest extends SingleShardRequest<GetRequest> implements RealtimeRequest 
    private String type;
    private String id;
    private String routing;
    private String parent;
    private String preference;
    private String[] storedFields;
    private FetchSourceContext fetchSourceContext;
    private boolean refresh = false;
    boolean realtime = true;
    private VersionType versionType;
    private long version;
    ......
    ...
    ...

在GetRequest对象中设置我们要查询的es索引(index)、类型(type)、 id、路由、分片、版本 等信息,也可以指定展示我们要查询的特定的列或排除的列信息FetchSourceContext。get查询是根据ID进行精确匹配的插叙,查询的参数封装在GetRequest中。

multiGet查询:

    public final MultiGetResponse multiGet(MultiGetRequest multiGetRequest, Header... headers) throws IOException 
        return (MultiGetResponse)this.performRequestAndParseEntity(multiGetRequest, Request::multiGet, MultiGetResponse::fromXContent, Collections.singleton(404), headers);
    

一次查询多个ID数据:

    @Test
    public void test2() throws IOException 
        String[] includes = new String[]"*", "birthday";
        String[] excludes = Strings.EMPTY_ARRAY;
        FetchSourceContext fetchSourceContext = new FetchSourceContext(true, includes, excludes);
        MultiGetRequest multiGetRequest = new MultiGetRequest();
        multiGetRequest.add(new MultiGetRequest.Item(index,type,"1").fetchSourceContext(fetchSourceContext)); //通过Item添加查询条件
        multiGetRequest.add(index,type,"2");  //直接添加查询条件
        MultiGetResponse multiGetItemResponses = client.multiGet(multiGetRequest);
        MultiGetItemResponse[] responses = multiGetItemResponses.getResponses();
        for(MultiGetItemResponse response : responses)
            System.out.println(response.getResponse().getSource().keySet().toString());
        
    

输出结果:

MultiGetRequest类内还定义了一个内部类Item,查询条件都封装在Item中。上面我们添加了两个查询条件,一个是通过Item内部类的构造函数添加,另一个是调用MultiGetRequest的add方法添加,其实都是创建一个新的Item对象。下面是add方法添加查询条件的源码:

    public MultiGetRequest add(String index, @Nullable String type, String id) 
        this.items.add(new MultiGetRequest.Item(index, type, id));
        return this;
    

search查询:
get查询我们只能根据ID进行精确查询,而search查询,我们可以自定义查询字段进行查询。

    public final SearchResponse search(SearchRequest searchRequest, Header... headers) throws IOException 
        return (SearchResponse)this.performRequestAndParseEntity(searchRequest, Request::search, SearchResponse::fromXContent, Collections.emptySet(), headers);
    

查询:

    @Test
    public void test3() 
        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
        sourceBuilder.from(0);
        sourceBuilder.size(10);
        sourceBuilder.fetchSource(new String[]"*", Strings.EMPTY_ARRAY);
        
        MatchQueryBuilder matchQueryBuilder = QueryBuilders.matchQuery("name", "rabbit");
        MultiMatchQueryBuilder multiMatchQueryBuilder = QueryBuilders.multiMatchQuery("YunZhiHui", "address", "company");
        TermQueryBuilder termQueryBuilder = QueryBuilders.termQuery("interest", "game steak");
        RangeQueryBuilder rangeQueryBuilder = QueryBuilders.rangeQuery("birthday");
        rangeQueryBuilder.gte("2018-01-26");
        rangeQueryBuilder.lte("2019-01-26");
        
        BoolQueryBuilder boolBuilder = QueryBuilders.boolQuery();
        boolBuilder.must(matchQueryBuilder);
        boolBuilder.must(termQueryBuilder);
        boolBuilder.must(rangeQueryBuilder);
        boolBuilder.should(multiMatchQueryBuilder);
        
        sourceBuilder.query(boolBuilder);
        SearchRequest searchRequest = new SearchRequest(index);
        searchRequest.types(type);
        searchRequest.source(sourceBuilder);
        try 
            SearchResponse response = client.search(searchRequest);
            System.out.println(response);
         catch (IOException e) 
            e.printStackTrace();
        
 
    

search查询的主要参数是SearchRequest,我们的查询条件index、type、字段、字段值 都封装在SearchRequest中;而index、type是直接封装在SearchRequest的对象中,查询的字段、字段值、查询方式则封装在SearchRequest中的对象属性SearchSourceBuilder中。

下面是SearchRequest的部分属性:

public final class SearchRequest extends ActionRequest implements Replaceable 
    private SearchType searchType;
    private String[] indices;
    @Nullable
    private String routing;
    @Nullable
    private String preference;
    private SearchSourceBuilder source;  //封装查询条件
    private Boolean requestCache;
    private Scroll scroll;
    private int batchedReduceSize;
    private int maxConcurrentShardRequests;
    private int preFilterShardSize;
    private String[] types; 
    private IndicesOptions indicesOptions;
    
    ......
    ......

从上面的test3中可以看出,要想构建出SearchSourceBuilder,还需要两个类:BoolQueryBuilder、QueryBuilders。BoolQueryBuilder用于构建bool查询的查询条件,也是在实际应用中使用较多的查询。QueryBuilder用于构建match、term、multiMatch等查询。如果我们的查询条件很简单,只需要match、term、multiMatch也可以不适用BoolQueryBuilder,而直接使用QueryBuilders构建出来的QueryBuilder对象。

以上是关于RestHighLevelClient查询ES的主要内容,如果未能解决你的问题,请参考以下文章

Es7.x使用RestHighLevelClient进行查询操作

中间件:ES组件RestHighLevelClient用法详解

Elasticsearch RestHighLevelClient客户端封装

列表分页查询

RestHighLevelClient操作ES的API

es索引的RestHighLevelClient实现