JAVA中Elasticsearch使用

文章目录

  • jar导入
  • 配置文件
  • ES工具类编写

jar导入

代码示例:

	   <!-- 阿里JSON解析器 -->
       <dependency>
           <groupId>com.alibaba</groupId>
           <artifactId>fastjson</artifactId>
           <version>1.2.78</version>
       </dependency>

       <!--ES-->
       <dependency>
           <groupId>org.springframework.boot</groupId>
           <artifactId>spring-boot-starter-data-elasticsearch</artifactId>
       </dependency>

配置文件

配置示例:

#ES配置
#ES连接地址
spring.elasticsearch.uris=ip:9200
#ES账号
spring.elasticsearch.username=username
#ES密码
spring.elasticsearch.password=password
spring.elasticsearch.connection-timeout=30s

ES工具类编写

代码示例:

package com.xxx;【修改引用地址】

import com.alibaba.fastjson.JSON;
import org.elasticsearch.action.delete.DeleteRequest;
import org.elasticsearch.action.delete.DeleteResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.action.support.WriteRequest;
import org.elasticsearch.action.update.UpdateRequest;
import org.elasticsearch.action.update.UpdateResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.core.TimeValue;
import org.elasticsearch.rest.RestStatus;
import org.springframework.stereotype.Service;

import java.io.IOException;

/**
 * ES工具包
 *
 * @author gxl
 */
@Service
public class EsUtils {

    /**
     * ES连接
     */
    public final RestHighLevelClient esClient;

    public EsUtils(RestHighLevelClient esClient) {
        this.esClient = esClient;
    }

    /**
     * 新增ES数据
     *
     * @param index  索引
     * @param id     id
     * @param object 新增实例
     * @return
     */
    public boolean index(String index, String id, Object object) {
        try {
            //创建ES客户端
            IndexRequest indexRequest = new IndexRequest(index)
                    .id(id)
                    .source(JSON.toJSONString(object), XContentType.JSON);
            //使用IMMEDIATE刷新策略【请求向ElasticSearch提交了数据,立即进行数据刷新,然后再结束请求】
            indexRequest.setRefreshPolicy(WriteRequest.RefreshPolicy.IMMEDIATE);
            //新增ES数据
            IndexResponse response = esClient.index(indexRequest, RequestOptions.DEFAULT);
            return response.getShardInfo().getFailed() == 0;
        } catch (Exception e) {
            System.out.println("添加缓存索引数据{}-异常==" + JSON.toJSONString(object) + "异常==" + e);
            return false;
        }
    }

    /**
     * 常规更新(更新部分字段)
     *
     * @param index  索引
     * @param id     id
     * @param object 修改实例
     * @throws IOException
     */
    public boolean updateById(String index, String id, Object object) throws IOException {
        try {
            //创建ES客户端
            UpdateRequest updateRequest = new UpdateRequest(index, id);
            //封存实例对象
            updateRequest.doc(JSON.toJSONString(object), XContentType.JSON);
            //设置响应时间
            updateRequest.timeout(TimeValue.timeValueSeconds(1));
            //使用WAIT_UNTIL刷新策略【请求向ElasticSearch提交了数据,等待数据完成刷新,然后再结束请求】
            updateRequest.setRefreshPolicy(WriteRequest.RefreshPolicy.WAIT_UNTIL);
            //常规更新(更新部分字段)
            UpdateResponse updateResponse = esClient.update(updateRequest, RequestOptions.DEFAULT);
            return RestStatus.OK.equals(updateResponse.status());
        } catch (Exception e) {
            System.out.println("添加缓存索引数据{}-异常==" + JSON.toJSONString(object) + "异常==" + e);
            return false;
        }
    }

    /**
     * saveOrUpdate更新模式(有则更新无则新增)
     *
     * @param index  索引
     * @param id     id
     * @param object 修改实例
     * @throws IOException
     */
    public boolean updateByIdUpsert(String index, String id, Object object) throws IOException {
        try {
            //创建ES客户端
            UpdateRequest updateRequest = new UpdateRequest(index, id);
            IndexRequest indexRequest = new IndexRequest(index, id).source(JSON.toJSONString(object), XContentType.JSON);
            //封存实例对象
            updateRequest.doc(indexRequest);
            updateRequest.docAsUpsert(true);
            //设置响应时间
            updateRequest.timeout(TimeValue.timeValueSeconds(1));
            //使用WAIT_UNTIL刷新策略【请求向ElasticSearch提交了数据,等待数据完成刷新,然后再结束请求】
            updateRequest.setRefreshPolicy(WriteRequest.RefreshPolicy.WAIT_UNTIL);
            //常规更新(更新部分字段)
            UpdateResponse updateResponse = esClient.update(updateRequest, RequestOptions.DEFAULT);
            return RestStatus.OK.equals(updateResponse.status());
        } catch (Exception e) {
            System.out.println("添加缓存索引数据{}-异常==" + JSON.toJSONString(object) + "异常==" + e);
            return false;
        }
    }
    
    /**
     * 根据ES某个字段更新ES信息示例
     */
    public static void main(String[] args) {
        HashMap<String, Object> map = new HashMap();
        map.put("updateFiled", "修改内容");
        BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
        boolQueryBuilder.must(QueryBuilders.termQuery("fieldName.keyword", "字段内容"));
        updateByQuery(ESConstants.SKU, boolQueryBuilder, map);
    }
	/**
     * 根据ES某个字段更新ES信息
     *
     * @param index            索引
     * @param boolQueryBuilder 修改条件
     * @param params           需要修改的参数
     * @throws IOException
     */
    public void updateByQuery(String index, BoolQueryBuilder boolQueryBuilder, HashMap<String, Object> params) throws IOException {
        UpdateByQueryRequest updateByQuery = new UpdateByQueryRequest(index);
        //设置分片并行
        updateByQuery.setSlices(2);
        //设置版本冲突时继续执行
        updateByQuery.setConflicts("proceed");
        //设置更新完成后刷新索引 ps很重要如果不加可能数据不会实时刷新
        updateByQuery.setRefresh(true);
        //painless 脚本拼接 ctx._source.pointsTypes = params.pointsTypes;
        StringBuilder idOrCode = new StringBuilder();
        for (String s : params.keySet()) {
            idOrCode.append("ctx._source.").append(s).append(" = params.").append(s).append(";");
        }
        //设置要修改的内容可以多个值多个用;隔开
        final Script script = new Script(
                ScriptType.INLINE, "painless",
                idOrCode.toString(),
                params);
        //修改条件
        updateByQuery.setQuery(boolQueryBuilder);
        updateByQuery.setScript(script);
        esClient.updateByQuery(updateByQuery, RequestOptions.DEFAULT);
    }

    /**
     * 根据ID删除数据
     * @param index 索引
     * @param id    id
     * @return
     */
    public boolean deleteById(String index, String id) {
        try {
            //创建ES客户端
            DeleteRequest request = new DeleteRequest(index)
                    .id(id);
            //根据ID删除数据
            DeleteResponse response = esClient.delete(request, RequestOptions.DEFAULT);
            return RestStatus.OK.equals(response.status());
        } catch (Exception e) {
            System.out.println("删除{}索引数据{}-异常==" + "index=" + index + "id=" + id + e);
            return false;
        }
    }

	/**
     * 根据ES字段删除ES信息
     * @param index
     * @param fieldName
     * @throws IOException
     */
    public void deleteEsByFieldName(String index, String fieldName) throws IOException {
        DeleteByQueryRequest request = new DeleteByQueryRequest();
        request.indices(index);
        BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
        boolQueryBuilder.must(QueryBuilders.termsQuery("fieldName.keyword", fieldName));
        request.setQuery(boolQueryBuilder);
        request.setRefresh(true);
        esClient.deleteByQuery(request, RequestOptions.DEFAULT);
    }
    
	/**
     * 根据Id查询ES信息
     * @param index 索引
     * @param id id
     * @return
     */
    public GetResponse findById(String index,String id) throws IOException {
        GetRequest request = new GetRequest();
        request.index(index).id(id);
        GetResponse response = esClient.get(request, RequestOptions.DEFAULT);
        return response;
    }
    
	/**
     * ES多条件查询(完全匹配查询)
     * @param index 索引
     * @param type 分区(增加过滤)
     * @param dataSource 单个查询条件
     * @param from 当前页(不传默认第0页)
     * @param size 每页查询条数(不传默认10条)
     * @return
     * @throws IOException
     */
    public List<Object> findESBy(String index,String type,String dataSource,Integer from,Integer size) throws IOException {
        //存放最终数据
        List<Object> list = new ArrayList<>();
        //1.创建搜索请求对象
        SearchRequest searchRequest = new SearchRequest(index).types(type);
        //2.设置搜索源配置
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
        //3.构建QueryBuilder对象指定查询方式和查询条件(完全匹配查询)
        QueryBuilder queryBuilder = QueryBuilders.matchPhraseQuery("查询条件", dataSource);
        //4,将QuseryBuilder对象设置到SearchSourceBuilder对象中
        searchSourceBuilder.query(queryBuilder);
        //当前页
        searchSourceBuilder.from(from);
        //每次查询条数
        searchSourceBuilder.size(size);
        //显示实际查询总条数
        searchSourceBuilder.trackTotalHits(true);
        //5,将SearchSourceBuilder设置到SearchRequest中
        searchRequest.source(searchSourceBuilder);
        try {
            //6,调用方法查询数据
            SearchResponse searchResponse = esClient.search(searchRequest, RequestOptions.DEFAULT);
            System.err.println("es语句:" + searchRequest);
            //7,解析返回结果
            SearchHits hits = searchResponse.getHits();
            //得到数据
            SearchHit[] searchHits = hits.getHits();
            for (SearchHit hit : searchHits){
                    list.add(hit.getSourceAsMap());
                }
            } catch (IOException e) {
            e.printStackTrace();
            }
        return list;
    }

	/**
     * ES多条件查询(模糊匹配查询)
     * @param index 索引
     * @param filedName 属性名称
     * @param dataSource 搜索值
     * @param from 当前页
     * @param size 每次查询条数
     * @return
     */
    public List<Object> findESSearch(String index,String filedName,String dataSource,Integer from,Integer size) {
            //存放最终数据
            List<Object> list = new ArrayList<>();
            //1.创建搜索请求对象
            SearchRequest searchRequest = new SearchRequest(index);
            //2.设置搜索源配置
            SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
            //3.创建搜索条件
            BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
            //根据所属字段前后匹配模糊查询
            boolQueryBuilder.must(QueryBuilders.wildcardQuery(filedName, "*" + dataSource + "*"));
            //4,将QuseryBuilder对象设置到SearchSourceBuilder对象中
            searchSourceBuilder.query(boolQueryBuilder);
            //当前页
            searchSourceBuilder.from(from);
            //每次查询条数
            searchSourceBuilder.size(size);
            //5,将SearchSourceBuilder设置到SearchRequest中
            searchRequest.source(searchSourceBuilder);
            try {
                //6,调用方法查询数据
                SearchResponse searchResponse = esClient.search(searchRequest, RequestOptions.DEFAULT);
                System.err.println("es语句:" + searchRequest);
                //7,解析返回结果
                SearchHit[] searchHits = searchResponse.getHits().getHits();
                //根据测试这里可以用hits变量替换searchHits变量
                for (SearchHit hit : searchHits) {
                    //获取文档内容
                    list.add(hit.getSourceAsString());
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        return list;
    }
}


你可能感兴趣的:(JAVA工具包,elasticsearch,java,搜索引擎)