【Elasticsearch8】

java elasticsearch8 单节点配置api

es8 相关依赖

    <dependency>
        <groupId>co.elastic.clients</groupId>
        <artifactId>elasticsearch-java</artifactId>
        <version>8.9.1</version>
    </dependency>
    <dependency>
        <groupId>jakarta.json</groupId>
        <artifactId>jakarta.json-api</artifactId>
        <version>2.0.1</version>
    </dependency>
    <dependency>
        <groupId>org.elasticsearch.client</groupId>
        <artifactId>elasticsearch-rest-client</artifactId>
        <version>8.9.1</version>
    </dependency>
    <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-core</artifactId>
        <version>2.13.3</version>
    </dependency>

es 配置

public class ElasticSearchConfig {

    private int port;
    private String url;
    private String userName;
    private String passWord;

    @Bean
    public ElasticsearchClient elasticsearchClient(){
        final CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
        credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(userName, passWord));
        RestClient restClient = RestClient.builder(new HttpHost(url, port, "http"))
                .setHttpClientConfigCallback(new RestClientBuilder.HttpClientConfigCallback() {
                    @Override
                    public HttpAsyncClientBuilder customizeHttpClient(HttpAsyncClientBuilder httpClientBuilder) {
                        return httpClientBuilder.setKeepAliveStrategy(DefaultConnectionKeepAliveStrategy.INSTANCE)
                                .setDefaultCredentialsProvider(credentialsProvider);
                    }
                }).build();
        ElasticsearchTransport transport = new RestClientTransport(restClient, new JacksonJsonpMapper());
        return new ElasticsearchClient(transport);
    }

}

es工具类

public class ESUtils {

    private String prefix="";
    @Resource
    private ElasticsearchClient client;

    /**
     * 创建index
     */
    public void createIndex(String indexName) {
        String finalIndex = prefix+indexName;
        try {
            client.indices().create(c -> c.index(finalIndex));
        } catch (Exception e) {
            log.error("create index error=", e);
        }
    }

    /**
     *  判断index是否存在
     */
    public boolean existsIndex(String indexName) {
        String finalIndex = prefix+indexName;
        try {
            BooleanResponse booleanResponse = client.indices().exists(e -> e.index(finalIndex));
            return booleanResponse.value();
        } catch (Exception e) {
            log.error("exists index error=", e);
        }
        return false;
    }

    /**
     * 删除index
     */
    public DeleteIndexResponse deleteIndex(String indexName) {
        String finalIndex = prefix+indexName;
        try {
            return client.indices().delete(d -> d.index(finalIndex));
        } catch (Exception e) {
            log.error("delete index error=", e);
        }
        return null;
    }

    /**
     * 新增数据
     */
    public <T> IndexResponse addDocument(String indexName, String id, T doc) {
        String finalIndex = prefix+indexName;
        try{
            return client.index(i -> i
                    .index(finalIndex)
                    .id(id)
                    .document(doc));
        } catch (Exception e) {
            log.error("add document error=", e);
        }
        return null;
    }

    public <T> void batchAddDocument(String indexName, List<String> idList,List<T> tList) throws IOException {
        if (CollectionUtils.isEmpty(tList)||CollectionUtils.isEmpty(idList)||idList.size()!=tList.size()){
            return;
        }
        String finalIndex = prefix+indexName;
        List<BulkOperation> list = new ArrayList<>();
        for (int i = 0; i < tList.size(); i++) {
            int finalI = i;
            list.add(BulkOperation.of(b->b.index(c->c.id(idList.get(finalI)).document(tList.get(finalI)))));
        }
        BulkResponse bulkResponse = client.bulk(b -> b.index(finalIndex).operations(list));
    }

    /**
     * 更新Document
     */
    public <T> UpdateResponse updateDocument(String indexName, String id, T doc, Class<T> clazz) {
        String finalIndex = prefix+indexName;
        try{
            return client.update(u -> u
                            .index(finalIndex)
                            .id(id)
                            .doc(doc), clazz);
        } catch (Exception e) {
            log.error("update document error=", e);
        }
        return null;
    }

    /**
     * 根据Id查询数据
     */
    public <T> T getById(String indexName, String id, Class<T> clazz) {
        String finalIndex = prefix+indexName;
        try {
            GetResponse<T> response = client.get(g -> g
                            .index(finalIndex)
                            .id(id), clazz);
            if (response.found()){
                return response.source();
            }
        } catch (Exception e) {
            log.error("get document error=", e);
        }
        return null;
    }

    /**
     * 查询列表
     */
    public <T> List<T> search(String indexName, Query query,String sortField, SortOrder order, Class<T> clazz) {
        String finalIndex = prefix+indexName;
        List<T> list = new ArrayList<>();
        try {
            SearchResponse<T> searchResponse = client.search(e -> e
                    .index(finalIndex)
                    .query(query)
                    .sort(sort -> sort.field(f -> f.field(sortField).order(order)))
                    , clazz);
            for (Hit<T> hit : searchResponse.hits().hits()) {
                T source = hit.source();
                list.add(source);
            }
        } catch (IOException e) {
            e.printStackTrace();
            log.error("search document error=", e);
        }
        return list;
    }

    //List<Query> queryList = new ArrayList<>();
    //queryList.add(MatchQuery.of(m->m.field("userId").query(50))._toQuery());
    //queryList.add(MatchQuery.of(m->m.field("type").query(7))._toQuery());
    public <T> List<T> search(String indexName, List<Query> queryList,String sortField, SortOrder order, Class<T> clazz) {
        String finalIndex = prefix+indexName;
        List<T> list = new ArrayList<>();
        try {
            SearchResponse<T> searchResponse = client.search(e -> e
                            .index(finalIndex)
                            .query(q->q.bool(b->b.must(queryList)))
                            .sort(sort -> sort.field(f -> f.field(sortField).order(order)))
                    , clazz);
            for (Hit<T> hit : searchResponse.hits().hits()) {
                T source = hit.source();
                list.add(source);
            }
        } catch (IOException e) {
            e.printStackTrace();
            log.error("search document error=", e);
        }
        return list;
    }

    /**
     * 获取最新的一条数据
     */
    public <T> T getLastDoc(String indexName, List<Query> queryList, String sortField, SortOrder order, Class<T> clazz) throws Exception {
        String finalIndex = prefix+indexName;
        SearchResponse<T> searchResponse = client.search(e -> e
                        .index(finalIndex)
                        .query(q->q.bool(b->b.must(queryList)))
                        .sort(sort -> sort.field(f -> f.field(sortField).order(order)))
                        .size(1)
                , clazz);
        List<Hit<T>> hitList = searchResponse.hits().hits();
        if (!CollectionUtils.isEmpty(hitList)){
            return hitList.get(0).source();
        }
        return null;
    }

    public boolean delById(String indexName,String id){
        String finalIndex = prefix+indexName;
        DeleteResponse delete = null;
        try {
            delete = client.delete(d -> d.index(finalIndex).id(id));
            return true;
        } catch (IOException e) {
            e.printStackTrace();
            log.error("del document error=", e);
        }
        return false;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值