Java中使用ElasticSerach【CentOS7.5 + ES7】

news/2025/2/25 22:56:53

1、所有文章优先发表在个人博客上: https://www.xdx97.com

2、后续如果有修改的话,可能忘记更新到CSDN了,给你带来不便,抱歉。

3、个人博客本篇文章地址 : https://www.xdx97.com/article?bamId=643946768060383232


必须要吐槽一下这个ES
1、很多方法弃用(好吧,这个应该夸他更新快吗),版本不向下兼容。也没找到好的文档。
2、Java连接有三种连接方式,找了半天。也不知道到底那个好
3、这个文档,是我一点一点折磨出来的
4、行了,我知道我菜,但是我不让说

这个是ES使用high-level-client的官方文档: https://www.elastic.co/guide/en/elasticsearch/client/java-rest/current/java-rest-high-search.html

1、我学习的时候网上很多教程,写的很详细。但是有的代码太多,有的代码太复杂,导致学习起来困难。当然了也可能是我太菜,所以我尽可能的把这个文档写的简单简单,再简单点。 有不懂的可以在我博客留言,我会尽快回复的。

1、因为简单,所以封装性可能不太好。但是没关系,你完全可以按照自己的想法去封装


准备工作:在你的CentOS上安装好你的ES和kibana并且可以访问。

1、Linux安装ElasticSearch【centOs7,ElasticSearch7.4.2】
2、CentOS/Linux安装kibana【CenOs7.3,kibana7.4.2】


1、添加Maven依赖    Maven仓库地址      因为导入的依赖要和你安装的版本一致,所以具体依赖版本按照自己的来

 <!-- ElasticSerach依赖 -->
 <dependency>
 	<groupId>org.elasticsearch</groupId>
 	<artifactId>elasticsearch</artifactId>
 	<version>7.4.2</version>
 </dependency>
 <dependency>
        <groupId>org.elasticsearch.client</groupId>
        <artifactId>elasticsearch-rest-high-level-client</artifactId>
        <version>7.4.2</version>
 </dependency>

2、相关代码

2-1:ElasticSerachUtils.java

package com.xdx.common.utils;

import com.xdx.common.config.ESProperties;
import org.apache.http.HttpHost;
import org.apache.poi.ss.formula.functions.T;
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.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.action.update.UpdateRequest;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.unit.TimeValue;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;

import java.io.IOException;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * ElasticSerach 工具栏
 *
 * @author 小道仙
 * @date 2019年11月14日
 */
public class ElasticSerachUtils {


    /**
     * 新增或者修改,修改的时候直接覆盖之前的数据
     *
     * @param index 索引,对应数据库的库
     * @param type  对应数据库的表
     * @param id 每一条数据的id
     * @param map 实际要存储的数据
     *
     * @author 小道仙
     * @date 2019年11月14日
     */
    public static void insertOrUpdate(String ip,Integer port,String index,String type,String id,Map map) throws IOException {
        RestHighLevelClient client = new RestHighLevelClient(RestClient.builder(new HttpHost(ip, port, "http")));
        IndexRequest indexRequest = new IndexRequest(index, type, id).source(map);
        client.index(indexRequest,RequestOptions.DEFAULT);
        client.close();
    }

    /**
     * 删除数据
     *
     * @param esProperties 基本配置文件
     * @param index 索引
     * @param id
     *
     * @author 小道仙
     * @date 2019年11月14日
     */
    public static void delete(String ip,Integer port,String index,String id) throws IOException {
        RestHighLevelClient client = new RestHighLevelClient(RestClient.builder(new HttpHost(ip, port, "http")));
        DeleteRequest request = new DeleteRequest(index, id);
        DeleteResponse delete = client.delete(request, RequestOptions.DEFAULT);
        System.out.println(delete.status() + "~" + delete.getResult());
        client.close();
    }

    /**
     * 更新数据
     *
     * 这个更新不会覆盖之前的数据,如果之前存在一个key(aaa),你这次更新没有key(aaa)。那么这个key(aaa)的数据不会被覆盖
     * @param esProperties 基本配置文件
     * @param index 索引
     * @param id
     * @param map 更新的数据
     *
     * @author 小道仙
     * @date 2019年11月14日
     */
    public static void update(String ip,Integer port,String index,String id,Map map) throws IOException {
        RestHighLevelClient client = new RestHighLevelClient(RestClient.builder(new HttpHost(ip, port, "http")));
        UpdateRequest request = new UpdateRequest(index, id).doc(map);
        client.update(request, RequestOptions.DEFAULT);
        client.close();
    }

    /**
     * 根据ID 获取数据
     */
    public static T  getById(String ip,Integer port,String index,String id) throws IOException {
        RestHighLevelClient client = new RestHighLevelClient(RestClient.builder(new HttpHost(ip, port, "http")));
        GetRequest posts = new GetRequest(index, id);
        GetResponse response = client.get(posts, RequestOptions.DEFAULT);
        System.out.println(response);
        client.close();
        return null;
    }

    /**
     * 根据index 获取数据
     */
    public static void getByIndex(String ip,Integer port,String index) throws IOException {
        RestHighLevelClient client = new RestHighLevelClient(RestClient.builder(new HttpHost(ip, port, "http")));
        SearchRequest searchRequest = new SearchRequest(index);
        SearchResponse search = client.search(searchRequest, RequestOptions.DEFAULT);
        System.out.println(search);
        client.close();
    }


    /**
     * 高级查询 模板
     */
    public static void getHighQuery(String ip,Integer port, String index) throws IOException {
        RestHighLevelClient client = new RestHighLevelClient(RestClient.builder(new HttpHost(ip, port, "http")));
        SearchRequest searchRequest = new SearchRequest(index);
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
        HighlightBuilder highlightBuilder = new HighlightBuilder().numOfFragments(0).fragmentSize(500);;

        /*👇👇👇👇👇👇👇👇👇👇👇👇👇👇👇👇👇👇👇自定义部分👇👇👇👇👇👇👇👇👇👇👇👇👇👇👇👇👇👇👇👇👇👇*/

        // 两种查询选一个
        // 模糊查询 text 字段中 包含 三 的
        QueryBuilder matchQueryBuilder =  QueryBuilders.matchQuery("text", "三").analyzer("ik_max_word");

        // 条件查询 在bamTitle 和 bamDesc 字段都进行模糊匹配关键字是 "三" 的
//        QueryStringQueryBuilder queryBuilder = new QueryStringQueryBuilder("三");
//        queryBuilder.field("bamTitle").field("bamDesc");
//        searchSourceBuilder.query(queryBuilder);
//        highlightBuilder.field("bamTitle").field("bamDesc");


        /**
         * 高亮查询 一
         * 最简单的高亮查询
         *
         * 每一个field 都表示 字段名, 高亮部分为上面的条件搜索 三
         */
        highlightBuilder.field("text").field("name");
        /**
         * 高亮查询 二
         * 自定义高亮标签
         *
         * 每一个field 都表示 字段名, 高亮部分为上面的条件搜索 三
         */
//        highlightBuilder.preTags("<h2>");
//        highlightBuilder.postTags("</h2>");
//        highlightBuilder.field("text").field("name");
        /**
         * 高亮查询 三
         * 对每一个字段进行单独设置,highlighterType 里面都有那些值,我暂时没有研究,可以自行研究
         *
         * 每一个field 都表示 字段名, 高亮部分为上面的条件搜索 三
         */
//        HighlightBuilder.Field highlightTitle = new HighlightBuilder.Field("text");
//        highlightTitle.highlighterType("unified");
//        highlightBuilder.field(highlightTitle);

        /**
         * 分页查询
         *
         * from 起始页
         * size 每页条数
         */
//        searchSourceBuilder.from(1);
//        searchSourceBuilder.size(1);

        /**
         * 根据 _id 排序 _id 字段名
         */
//        searchSourceBuilder.sort(new FieldSortBuilder("text").order(SortOrder.ASC));

        /**
         * 选择性的查询字段
         * includeFields 要查询的字段名称
         * excludeFields 不查询的字段名称
         */
        String[] includeFields = new String[] {"text","name"};
        String[] excludeFields = new String[] {"id"};
        searchSourceBuilder.fetchSource(includeFields, excludeFields);

        /**
         * 设置超时时间
         */
        searchSourceBuilder.timeout(new TimeValue(60, TimeUnit.SECONDS));


        /*👆👆👆👆👆👆👆👆👆👆👆👆👆👆👆👆👆👆👆👆👆自定义部分👆👆👆👆👆👆👆👆👆👆👆👆👆👆👆👆👆👆👆👆👆*/

        searchSourceBuilder.highlighter(highlightBuilder);
        searchSourceBuilder.query(matchQueryBuilder);
        searchRequest.source(searchSourceBuilder);
        SearchResponse search = client.search(searchRequest, RequestOptions.DEFAULT);
        System.out.println(search);
        client.close();
    }


}

2-2:ElasticSerachController.java

package com.xdx.service.api.elasticserach;

import com.xdx.core.domain.AjaxResult;
import org.springframework.web.bind.annotation.GetMapping;

import java.io.IOException;

/**
 * ElasticSerach 相关操作
 *
 * @author 小道仙
 * @date 2019年11月13日
 */
public interface ElasticSerachController {

    /**
     * 新增一个文档操作
     */
    @GetMapping("/elasticSerach/addDocment")
    AjaxResult<?> addDocment() throws IOException;

    /**
     * 删除一个文档操作
     */
    @GetMapping("/elasticSerach/delete")
    AjaxResult<?> delete() throws IOException;

    /**
     * 更新一个文档操作
     */
    @GetMapping("/elasticSerach/update")
    AjaxResult<?> update() throws IOException;

    /**
     * 根据ID获取相关信息
     */
    @GetMapping("/elasticSerach/getById")
    AjaxResult<?> getById() throws IOException;

    /**
     * 高级搜索
     */
    @GetMapping("/elasticSerach/getHigh")
    AjaxResult<?> getHigh() throws IOException;
}

2-3:ElasticSerachService.java

package com.xdx.service.elasticserach;

import com.xdx.common.utils.ElasticSerachUtils;
import com.xdx.core.domain.AjaxResult;
import com.xdx.service.api.elasticserach.ElasticSerachController;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;


/**
 *  map 就是要存储的数据
 *  index、type。 就是同ES里面的index和type。这里为了可读性,我就不再去别名了。你测试的时候随意
 *  你可以手动插入一些数据然后测试,也可以先调用插入数据方法去添加数据
 *
 */

@RestController
@Transactional
public class ElasticSerachService implements ElasticSerachController {
    
    private final String ip = "127.0.0.1";

    private final Integer port = 9000;  


    @Override
    public AjaxResult<?> addDocment() throws IOException{
        Map map = new HashMap();
        map.put("serach","ccccc");
        ElasticSerachUtils.insertOrUpdate(ip,port,"index","type","123456",map);
        return null;
    }

    @Override
    public AjaxResult<?> delete() throws IOException {
        ElasticSerachUtils.delete(ip,port,"index","123456");
        return null;
    }

    @Override
    public AjaxResult<?> update() throws IOException {
        Map map = new HashMap();
        map.put("date","aaaaaa");
        ElasticSerachUtils.update(ip,port,"index","123456",map);
        return null;
    }

    @Override
    public AjaxResult<?> getById() throws IOException {
        ElasticSerachUtils.getById(ip,port,"index","123456");
        return null;
    }


    @Override
    public AjaxResult<?> getHigh() throws IOException {
        ElasticSerachUtils.getHighQuery(ip,port,"index");
        return null;
    }

}
![在这里插入图片描述](https://img-blog.csdnimg.cn/20191118144336221.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L1RvbXdpbGRib2Fy,size_16,color_FFFFFF,t_70)
**你如果只是做简单测试,controller和service直接用一个。utils和他们放一起就好了。**

http://www.niftyadmin.cn/n/775022.html

相关文章

PHPshua单交易任务平台源码 附带搭建教程

介绍&#xff1a; PHPshua单交易任务平台源码[附带搭建教程] 把源码上传到根目录&#xff0c;导入数据库文件“sjk.sql” 打开/protected/config/main.php文件&#xff0c;定位到第67行&#xff0c;并根据提示配置您的数据库信息&#xff01; 修改目录/protected/config/de…

超好看的网站极简导航网址网站源码模板

介绍&#xff1a; 超好看的网站极简导航网址网站源码模板 网盘下载地址&#xff1a; http://kekewl.org/vMD3vuKtwrC 图片&#xff1a;

ElasticSerach安装IK中文分词器,并在Java中使用

1、所有文章优先发表在个人博客上&#xff1a; https://www.xdx97.com 2、后续如果有修改的话&#xff0c;可能忘记更新到CSDN了&#xff0c;给你带来不便&#xff0c;抱歉。 3、个人博客本篇文章地址 &#xff1a; https://www.xdx97.com/article?bamId644470506396844032 1、…

全新PHP小鬼授权系统修改版源码

介绍&#xff1a; 全新PHP小鬼授权源码系统解密版&#xff0c;源码自带独家有效完美防黑功能&#xff0c;去除一些广告和bug 网盘下载地址&#xff1a; http://kekewl.org/FoSEoRcMKes 图片&#xff1a;

ElasticSerach相关命令

1、所有文章优先发表在个人博客上&#xff1a; https://www.xdx97.com 2、后续如果有修改的话&#xff0c;可能忘记更新到CSDN了&#xff0c;给你带来不便&#xff0c;抱歉。 3、个人博客本篇文章地址 &#xff1a; https://www.xdx97.com/article?bamId644504271890415616 查…

香橙互赞网系统源码 美化模板

介绍&#xff1a; 模板适用于香橙系统&#xff0c;其他需要自己修改。 上传到网站根目录解压 覆盖即可(建议先备份源文件) 网盘下载地址&#xff1a; http://kekewangLuo.net/91CXB3SHBKi 图片&#xff1a;

Data too large data for

1、所有文章优先发表在个人博客上&#xff1a; https://www.xdx97.com 2、后续如果有修改的话&#xff0c;可能忘记更新到CSDN了&#xff0c;给你带来不便&#xff0c;抱歉。 3、个人博客本篇文章地址 &#xff1a; https://www.xdx97.com/article?bamId644536524079104000 简…

ElasticSerach编写Shell启动脚本

1、所有文章优先发表在个人博客上&#xff1a; https://www.xdx97.com 2、后续如果有修改的话&#xff0c;可能忘记更新到CSDN了&#xff0c;给你带来不便&#xff0c;抱歉。 3、个人博客本篇文章地址 &#xff1a; https://www.xdx97.com/article?bamId644536524079104000 文…