ElasticSearch工具类

EsUtil主体功能
package com.example.demo.util.es;

import com.alibaba.fastjson.JSON;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.http.HttpEntity;
import org.apache.http.entity.ContentType;
import org.apache.http.nio.entity.NStringEntity;
import org.apache.http.util.EntityUtils;
import org.elasticsearch.action.ActionListener;
import org.elasticsearch.action.DocWriteResponse;
import org.elasticsearch.action.admin.indices.alias.get.GetAliasesRequest;
import org.elasticsearch.action.admin.indices.delete.DeleteIndexRequest;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.delete.DeleteRequest;
import org.elasticsearch.action.delete.DeleteResponse;
import org.elasticsearch.action.get.GetRequest;
import org.elasticsearch.action.get.GetResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.action.support.master.AcknowledgedResponse;
import org.elasticsearch.action.update.UpdateRequest;
import org.elasticsearch.action.update.UpdateResponse;
import org.elasticsearch.client.*;
import org.elasticsearch.client.indices.GetIndexRequest;
import org.elasticsearch.common.text.Text;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.WildcardQueryBuilder;
import org.elasticsearch.index.reindex.BulkByScrollResponse;
import org.elasticsearch.index.reindex.ReindexRequest;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.FetchSourceContext;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;

import java.io.IOException;
import java.util.*;

/**
 * @author Mr.Ye
 * @version 1.0.0
 * @create 2022-04-12
 * @description ElasticSearch工具类
 * @description 1、初学者建议使用easy-es框架,更加方便;https://easy-es.cn/#/quick-start
 */
public class EsUtil {

    private static Log log = LogFactory.getLog(EsUtil.class);

    /*请求处理时间*/
    private static final String TIME_OUT = "20s";
    private static final String ADD = "ADD";
    private static final String UPDATE = "UPDATE";
    private static final String DELETE = "DELETE";
    /*数据插入主键ID*/
    private static final String ES_ID = "ES_ID";

    private static final String ENDPOINT = "/_sql?format=json";

    /*获取dsl语句*/
    private static final String ENDPOINT_TRANSLATE = "/_sql/translate";


    /**
     * 向es中创建文档索引, 若es中已存在改index,则插入失败。
     *
     * @param indexName 索引名称
     * @param document  id
     * @param jsonStr   json字符串, 要存入的数据
     */
    public Boolean insertIndexWithJsonStr(String indexName, String document, String jsonStr) {
        Boolean indexExists = isIndexExists(indexName, document);
        Boolean result = false;
        if (!indexExists) {
            IndexRequest indexRequest = new IndexRequest(indexName).id(document).source(jsonStr, XContentType.JSON);
            IndexResponse indexResponse = null;
            try {
                indexResponse = EsServerManager.getInstance().getClient().index(indexRequest, RequestOptions.DEFAULT);
                if (indexResponse.getResult() == DocWriteResponse.Result.CREATED) {
                    result = true;
                }
                log.info(indexResponse.getIndex() + "--" + indexResponse.getId() + "--" + "插入成功");

            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return result;
    }

    /**
     * 批量处理数据
     *
     * @param indexName 索引名称
     * @param list      数据集合
     * @param type      类型 ADD-添加, UPDATE-更新, DELETE-删除
     */
    public Boolean bulkIndex(String indexName, List<Map<String, Object>> list, String type) {
        BulkRequest bulkRequest = new BulkRequest();
        bulkRequest.timeout(TIME_OUT);
        Boolean result = false;
        for (int i = 0; i < list.size(); i++) {
            //批量添加数据
            //TODO id可以自己设置,这里默认为ES_ID
            if (ADD.equals(type)) {
                IndexRequest source = new IndexRequest(indexName).id(list.get(i).get(ES_ID).toString()).source(list.get(i));
                bulkRequest.add(source);
            } else if (UPDATE.equals(type)) {
                UpdateRequest updateRequest = new UpdateRequest(indexName, list.get(i).get(ES_ID).toString()).doc(list.get(i));
                bulkRequest.add(updateRequest);
            } else if (DELETE.equals(type)) {
                DeleteRequest deleteRequest = new DeleteRequest(indexName, list.get(i).get(ES_ID).toString());
                bulkRequest.add(deleteRequest);
            }
        }
        try {
            BulkResponse bulkResponse = EsServerManager.getInstance().getClient().bulk(bulkRequest, RequestOptions.DEFAULT);
            if (bulkResponse.hasFailures()) {
                /*是否失败,如果是false则成功*/
                log.error("批量插入失败,原因:" + bulkResponse.buildFailureMessage());
                return result;
            } else {
                result = true;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return result;
    }

    /**
     * 查询指定id下索引数据
     *
     * @param indexName 索引名称
     * @param document  id
     * @return 返回得到的字符串, 没有返回null
     * {"age":18,"id":1,"name":"xuchenglei"}
     */
    public String queryIndex(String indexName, String document) {
        Boolean indexExists = isIndexExists(indexName, document);
        if (indexExists) {
            GetResponse getResponse = null;
            GetRequest getRequest = new GetRequest(indexName, document);
            try {
                getResponse = EsServerManager.getInstance().getClient().get(getRequest, RequestO
  • 2
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值