ElasticSearch Java client 简单使用

2021-11-14 From 程序之心 By 丁仪

引入maven依赖

需要引入 elasticsearch 和 elasticsearch-rest-high-level-client,到 maven 仓库搜索最新版本。

创建客户端

HttpHost httpHost = new HttpHost("localhost",9200);
RestClientBuilder restClientBuilder = RestClient.builder(httpHost);
client = new RestHighLevelClient(restClientBuilder);
判断 index 是否存在
GetIndexRequest getIndexRequest = new GetIndexRequest(index);
getIndexRequest.humanReadable(true);
boolean exists = client.indices().exists(getIndexRequest, RequestOptions.DEFAULT);
创建 index
CreateIndexRequest request = new CreateIndexRequest(index);
Map properties = new HashMap<>();
autoBuildProperties(clazz, properties);
Map mapping = new HashMap<>();
mapping.put("properties", properties);
request.mapping(mapping);
client.indices().create(request, RequestOptions.DEFAULT);

异步插入或更新文档

IndexRequest request = new IndexRequest("index");
request.id(id);
request.source(beanToMap(object));
client.indexAsync(request, RequestOptions.DEFAULT, new ActionListener(){
    @Override
    public void onResponse(IndexResponse response) {
        //
    }

    @Override
    public void onFailure(Exception e) {
        //
    }
});
删除文档
DeleteRequest request = new DeleteRequest("index", String.valueOf(id));
client.deleteAsync(request, RequestOptions.DEFAULT, new ActionListener() {
    @Override
    public void onResponse(DeleteResponse deleteResponse) {
        //
    }

    @Override
    public void onFailure(Exception e) {
        //
    }
});
搜索
SearchRequest searchRequest = new SearchRequest("index");
SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
// 构造查询条件,这里是全都返回
sourceBuilder.query(QueryBuilders.matchAllQuery());
searchRequest.source(searchSourceBuilder(batchQuery));
SearchResponse response = client.search(searchRequest, RequestOptions.DEFAULT);


本文来源:程序之心,转载请注明出处!

本文地址:https://chengxuzhixin.com/blog/article/300449.html

发表感想

© 2016 - 2022 chengxuzhixin.com All Rights Reserved.

浙ICP备2021034854号-1    浙公网安备 33011002016107号