美文网首页
ElasticSearch Clients (Java)

ElasticSearch Clients (Java)

作者: 谁在烽烟彼岸 | 来源:发表于2020-05-19 17:18 被阅读0次

SpringBoot项目中集成ElasticSearchClient (version = 6.1.1),该版本相对老旧,对某些api的支持并不好,有条件的可以及时更新。

6.1 7.8
6.1 7.8

可见差别还是挺大的。
ps:本文使用6.1.1

配置

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.transport.TransportAddress;
import org.elasticsearch.transport.client.PreBuiltTransportClient;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import java.net.InetAddress;
import java.net.UnknownHostException;

@Configuration
public class ElaticSearchConfig {
    @Value("${spring.data.elasticsearch.cluster-nodes}")
    private String hosts;
    @Value("${spring.data.elasticsearch.cluster-port}")
    private Integer port;
    @Value("${spring.data.elasticsearch.cluster-name}")
    private String clusterName;
    private static final Logger logger = LogManager.getLogger(ElaticSearchConfig.class);
    @Bean
    public TransportClient client() {
        Settings settings = Settings.builder()
                .put("cluster.name", clusterName)
                .build();
        TransportClient client = null;
        try {
            client = new PreBuiltTransportClient(settings)
                        .addTransportAddress(new TransportAddress(InetAddress.getByName(hosts), port));
        } catch (UnknownHostException e) {
            e.printStackTrace();
        }
        logger.info("The es client create successful" + "host = " + hosts + ",port = " + port);
        return client;
    }
}

基础操作

// insert
Map<String, Object> page = pageEntity.toMap();
IndexResponse response = client.prepareIndex(index, type, id)
                .setSource(page)
                .get();
// get
GetResponse getResponse = client.prepareGet(index, type, id).get();
// delete
DeleteResponse response = client.prepareDelete(index, type, id).get();
// 删除/添加/获取多个,都可以使用该操作
BulkRequest request = new BulkRequest();
list.forEach(item -> {
            request.add(new DeleteRequest(index, type, item.getId()));
});
client.bulk(request);

对Index操作

//create
//可以在request上追加各种信息
CreateIndexRequest request = new CreateIndexRequest("away-log"); 
CreateIndexResponse createIndexResponse = client.indices().create(request, RequestOptions.DEFAULT);
//get
GetIndexRequest request = new GetIndexRequest().indices("index"); 
GetIndexResponse getIndexResponse = client.indices().get(request, RequestOptions.DEFAULT);

// delete
//注意indexs可以是一个索引 ,也可以是索引的数组
DeleteIndexResponse response = client.admin().indices().prepareDelete(indexs).get();
//getAll
GetIndexResponse response = client.admin()
                .indices()
                .prepareGetIndex()
                .execute()
                .actionGet();
//

搜索

//查询条件
BoolQueryBuilder where = QueryBuilders.boolQuery();
//按照日期进行分组
DateHistogramAggregationBuilder agg = AggregationBuilders.dateHistogram("agg")
                //字段
                .field("time")
                //时间间隔 
                .dateHistogramInterval(dateHistogramInterval)
                //输出的时间格式
                .format(model);
//设置时区
agg.timeZone(DateTimeZone.forID("+08:00"));
//按照用户分组
AggregationBuilder user = AggregationBuilders.terms("user").field("userId").size(Integer.MAX_VALUE);
//添加到前一个分组条件
agg.subAggregation(user);
 //排序
 SortBuilder sortBuilder = SortBuilders.fieldSort("score").order(SortOrder.DESC);
 SearchResponse response = client.prepareSearch("index")
                .setQuery(where)
                //起点
                .from(i)
                //size
                .setSize(size)
                .addSort(sortBuilder)
                .addAggregation(agg)
                .get();

相关文章

网友评论

      本文标题:ElasticSearch Clients (Java)

      本文链接:https://www.haomeiwen.com/subject/vochohtx.html