ElasticSearch 学习9 spring-boot ,elasticsearch7.16.1实现中文拼音分词搜索

news2024/9/29 11:35:29

一、elasticsearch官网下载:Elasticsearch 7.16.1 | Elastic

二、拼音、ik、繁简体转换插件安装

ik分词:GitHub - medcl/elasticsearch-analysis-ik: The IK Analysis plugin integrates Lucene IK analyzer into elasticsearch, support customized dictionary.

拼音分词:GitHub - medcl/elasticsearch-analysis-pinyin: This Pinyin Analysis plugin is used to do conversion between Chinese characters and Pinyin.

繁简体转换:GitHub - medcl/elasticsearch-analysis-stconvert: STConvert is analyzer that convert chinese characters between traditional and simplified.中文简繁體互相转换.

安装过程:从github上下载源码到本地,idea打开项目,修改对应项目中的pom.xml将

<elasticsearch.version>7.16.1</elasticsearch.version>修改为对应的elasticsearch版本

,alt+f12打开cmd命令界面,输入mvn install,项目编译成功后会在对应目录中生成对应zip包,效果如图:

将对应zip包解压到elasticsearch存放目录的plugins下:

重新给把lasticsearch的文件权限给用户elastic 

chown -R elastic /usr/local/elasticsearch-7.16.1/

不然报权限的错误哦

然后启动elasticsearch.bat,

这样对应插件就算安装成功了

三. mvn,及yml配置

  <elasticsearch.version>7.16.1</elasticsearch.version>

 <dependency>
            <groupId>org.elasticsearch</groupId>
            <artifactId>elasticsearch</artifactId>
            <version>${elasticsearch.version}</version>

        </dependency>
        <dependency>
            <groupId>org.elasticsearch.client</groupId>
            <artifactId>elasticsearch-rest-client</artifactId>
            <version>${elasticsearch.version}</version>
        </dependency>
        <dependency>
            <groupId>org.elasticsearch.client</groupId>
            <artifactId>transport</artifactId>
            <version>${elasticsearch.version}</version>
        </dependency>

        <dependency>
            <groupId>org.elasticsearch.client</groupId>
            <artifactId>elasticsearch-rest-high-level-client</artifactId>
            <version>${elasticsearch.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.data</groupId>
            <artifactId>spring-data-elasticsearch</artifactId>
            <version>3.1.3.RELEASE</version>
        </dependency>

        <dependency>
            <groupId>org.elasticsearch.plugin</groupId>
            <artifactId>x-pack-sql-jdbc</artifactId>
            <version>${elasticsearch.version}</version>
        </dependency>
  # ElasticSearch 7设置
  elasticsearch:
   
    schema: http
    host: 123.456
    port: 9200
    userName: es
    password:3333
    indexes: index

四. es工具类

此次在原来的基础上主要是加了创建索引时可选则索引库的默认分词器类型,可选pinyin

CreateIndexRequest request = new CreateIndexRequest(indexName);
request.settings(Settings.builder()
        //.put("analysis.analyzer.default.type", "ik_max_word")
        //.put("analysis.analyzer.default.type", "pinyin")//同时支持拼音和文字
        .put("analysis.analyzer.default.type", indexType)


import com.alibaba.fastjson.JSON;
import io.micrometer.core.instrument.util.StringUtils;
import org.apache.http.HttpHost;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.apache.lucene.search.TotalHits;
import org.elasticsearch.action.DocWriteResponse;
import org.elasticsearch.action.admin.indices.create.CreateIndexRequest;
import org.elasticsearch.action.admin.indices.create.CreateIndexResponse;
import org.elasticsearch.action.admin.indices.delete.DeleteIndexRequest;
import org.elasticsearch.action.admin.indices.get.GetIndexRequest;
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.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.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestClientBuilder;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.text.Text;
import org.elasticsearch.common.unit.TimeValue;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.QueryStringQueryBuilder;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @author ylwang
 * @create 2021/7/27 9:16
 */
@Configuration
public class ElasticSearchClientConfig {

    /**
     * 协议
     */
    @Value("${jeecg.elasticsearch.schema}")
    private String schema;

    /**
     * 用户名
     */
    @Value("${jeecg.elasticsearch.userName}")
    private String userName;

    /**
     * 密码
     */
    @Value("${jeecg.elasticsearch.password}")
    private String password;

    /**
     * 地址
     */
    @Value("${jeecg.elasticsearch.host}")
    private String host;

    /**
     * 地址
     */
    @Value("${jeecg.elasticsearch.port}")
    private String port;

    public final   String   AIOPENQAQINDEXNAME = "aiopenqaq"; //ai问题库索引名
    public final   String   AIYunLiao = "aiyunliao"; //ai语料库索引名
    public final   String   KNOWLEDGE = "knowledge";//知识库索引名

    public static RestHighLevelClient restHighLevelClient;

    @Bean
    public RestHighLevelClient restHighLevelClient() {
        restHighLevelClient = new RestHighLevelClient(RestClient.builder(
                new HttpHost(host, Integer.parseInt(port), schema)));
        //验证用户密码
        final CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
        credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(userName, password));
        RestClientBuilder restClientBuilder = RestClient
                .builder(new HttpHost(host, Integer.parseInt(port), schema))
                .setHttpClientConfigCallback(httpClientBuilder -> {
                    httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider);
                    return httpClientBuilder;
                })
                .setRequestConfigCallback(requestConfigBuilder -> {
                    return requestConfigBuilder;
                });

        restHighLevelClient = new RestHighLevelClient(restClientBuilder);
        return restHighLevelClient;
    }
    /**
     * 判断索引是否存在
     * @return 返回是否存在。
     * 		<ul>
     * 			<li>true:存在</li>
     * 			<li>false:不存在</li>
     * 		</ul>
     */
    public boolean existIndex(String index){
        GetIndexRequest request = new GetIndexRequest();
        request.indices(index);
        boolean exists;
        try {
            exists = restHighLevelClient().indices().exists(request, RequestOptions.DEFAULT);
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        }
        return exists;
    }


    /**
     * 查询并分页
     * @param indexName 索引名字
     * @param from 从第几条开始查询,相当于 limit a,b 中的a ,比如要从最开始第一条查,可传入: 0
     * @param size 本次查询最大查询出多少条数据 ,相当于 limit a,b 中的b
     * @return {@link SearchResponse} 结果,可以通过 response.status().getStatus() == 200 来判断是否执行成功
     *获取总条数的方法
     * TotalHits totalHits = searchResponse.getHits().getTotalHits();
     *
     */
    public SearchResponse search(String indexName, SearchSourceBuilder searchSourceBuilder, Integer from, Integer size){
        SearchRequest request = new SearchRequest(indexName);
        searchSourceBuilder.from(from);
        searchSourceBuilder.size(size);
        request.source(searchSourceBuilder);
        SearchResponse response = null;
        try {
            response = restHighLevelClient().search(request, RequestOptions.DEFAULT);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return response;
    }

    /**
     * 根据索引中的id查询
     * @param indexName
     * @param id
     * @return
     */
    public String searchById(String indexName,String id){
        SearchRequest request = new SearchRequest(indexName);
        request.source(new SearchSourceBuilder().query(QueryBuilders.termQuery("_id",id)));
        SearchResponse response = null;
        try {
            response = restHighLevelClient().search(request, RequestOptions.DEFAULT);
            SearchHits hits = response.getHits();
            SearchHit[] hits1 = hits.getHits();
            for (SearchHit fields : hits1) {
                return fields.getSourceAsString();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 创建索引
     *
     * @param indexName 要创建的索引的名字,传入如: testindex
     * @param indexType 索引类型 : ik_max_word 和 pinyin
     * @return 创建索引的响应对象。可以使用 {@link CreateIndexResponse#isAcknowledged()} 来判断是否创建成功。如果为true,则是创建成功
     */
    public CreateIndexResponse createIndex(String indexName,String indexType)  {
        CreateIndexResponse response=null;
        if(existIndex(indexName)){
            response = new CreateIndexResponse(false, false, indexName);
            return response;
        }
        if(StringUtils.isBlank(indexType)){
            indexType="ik_max_word";
        }
        CreateIndexRequest request = new CreateIndexRequest(indexName);
        request.settings(Settings.builder()
                //.put("analysis.analyzer.default.type", "ik_max_word")
                //.put("analysis.analyzer.default.type", "pinyin")//同时支持拼音和文字
                .put("analysis.analyzer.default.type", indexType)
        );
        try {
            response = restHighLevelClient().indices().create(request, RequestOptions.DEFAULT);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return response;
    }

    /**
     * 数据添加,网 elasticsearch 中添加一条数据
     * @param params 要增加的数据,key-value形式。 其中map.value 支持的类型有 String、int、long、float、double、boolean
     * @param indexName 索引名字,类似数据库的表,是添加进那个表
     * @param id 要添加的这条数据的id, 如果传入null,则由es系统自动生成一个唯一ID
     * @return 创建结果。如果 {@link IndexResponse#getId()} 不为null、且id长度大于0,那么就成功了
     */
    public IndexResponse put(String params, String indexName, String id){
        //创建请求
        IndexRequest request = new IndexRequest(indexName);
        if(id != null){
            request.id(id);
        }
        request.timeout(TimeValue.timeValueSeconds(5));
        IndexResponse response = null;
        try {
            response = restHighLevelClient().index(request.source(params, XContentType.JSON).setRefreshPolicy("wait_for"), RequestOptions.DEFAULT);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return response;
    }

    /**
     * 数据更新
     * @param params 要更新 的数据,key-value形式。 其中map.value 支持的类型有 String、int、long、float、double、boolean
     * @param indexName 索引名字,类似数据库的表,是添加进那个表
     * @param id 要添加的这条数据的id, 如果传入null,则由es系统自动生成一个唯一ID
     * @return 创建结果。如果 {@link IndexResponse#getId()} 不为null、且id长度大于0,那么就成功了
     */
    public UpdateResponse update(String params, String indexName, String id){
        //创建请求
        UpdateRequest request = new UpdateRequest(indexName,id);
        request = request.doc(params, XContentType.JSON);
        request.setRefreshPolicy("wait_for");
        request.timeout(TimeValue.timeValueSeconds(5));
        UpdateResponse response = null;
        try {
            response = restHighLevelClient().update(request, RequestOptions.DEFAULT);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return  response;
    }


    /**
     * 删除索引
     * @param indexName
     * @throws IOException
     */
    public AcknowledgedResponse deleteIndex(String indexName)   {
        DeleteIndexRequest request = new DeleteIndexRequest(indexName);
        AcknowledgedResponse response = null;
        try {
            response = restHighLevelClient().indices().delete(request, RequestOptions.DEFAULT);
        } catch (IOException e) {
            e.printStackTrace();
        }
        System.out.println(response.isAcknowledged());

        return response;
    }


    /**
     * 通过elasticsearch数据的id,来删除这条数据
     * @param indexName 索引名字
     * @param id 要删除的elasticsearch这行数据的id
     */
    public boolean deleteById(String indexName, String id) {
        DeleteRequest request = new DeleteRequest(indexName, id);
        request.setRefreshPolicy("wait_for");
        DeleteResponse delete = null;
        try {
            delete = restHighLevelClient().delete(request, RequestOptions.DEFAULT);

        } catch (IOException e) {
            e.printStackTrace();
            //删除失败
            return false;
        }

        if(delete == null){
            //这种情况应该不存在
            return false;
        }
        if(delete.getResult().equals(DocWriteResponse.Result.DELETED)){
            return true;
        }else{
            return false;
        }
    }






}

五,创建索引,插入数据

@Resource
private ElasticSearchClientConfig es;

@Resource
private AiOpenqaQMapper aiOpenqaQMapper;



    @Override
    public int selectNums(String applicationId) {
        return aiOpenqaQMapper.selectNums(applicationId);
    }

    @Override
    public boolean saveAndEs(AiOpenqaQ aiOpenqaQ) {
       // es.deleteIndex(es.AIOPENQAQINDEXNAME);
        boolean save = this.save(aiOpenqaQ);
        if(save){
            if(!es.existIndex(es.AIOPENQAQINDEXNAME)){
                es.createIndex(es.AIOPENQAQINDEXNAME,"pinyin");
            }
            es.put(JsonMapper.toJsonString(aiOpenqaQ), es.AIOPENQAQINDEXNAME,aiOpenqaQ.getId());
        }
        return true;
    }
}

六,验证

同音词查询

直接拼音

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/1379142.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

python 异常处理 try...except...finally..

python 异常处理&#xff1a; 简单的异常处理主要依靠内置异常处理结构体&#xff0c;代码结构如下&#xff1a; try: … except ValueError as e: # 异常判断&#xff0c;出现ValueError错误时处理机制 … except ZeroDivisionError as e: # 异常判断&#xff0c;出现ZeroDiv…

书生·浦语大模型--第二节课笔记

书生浦语大模型--第二节课 大模型及InternLM基本介绍实战部分demo部署准备工作模型下载代码准备终端运行web demo 运行 Lagent 智能体工具调用 Demo准备工作Demo 运行 浦语灵笔图文理解创作 Demo环境准备下载模型下载代码运行 大模型及InternLM基本介绍 大模型 定义&#xff…

数据结构中的一棵树

一、树是什么&#xff1f; 有根有枝叶便是树&#xff01;根只有一个&#xff0c;枝叶可以有&#xff0c;也可以没有&#xff0c;可以有一个&#xff0c;也可以有很多。 就像这样&#xff1a; 嗯&#xff0c;应该是这样&#xff1a; 二、一些概念 1、高度 树有多高&#x…

案例117:基于微信小程序的新闻资讯系统设计与实现

文末获取源码 开发语言&#xff1a;Java 框架&#xff1a;springboot JDK版本&#xff1a;JDK1.8 数据库&#xff1a;mysql 5.7 开发软件&#xff1a;eclipse/myeclipse/idea Maven包&#xff1a;Maven3.5.4 小程序框架&#xff1a;uniapp 小程序开发软件&#xff1a;HBuilder …

Spring Boot - Application Events 的发布顺序_ApplicationStartedEvent

文章目录 Pre概述Code源码分析 Pre Spring Boot - Application Events 的发布顺序_ApplicationEnvironmentPreparedEvent 概述 Spring Boot 的广播机制是基于观察者模式实现的&#xff0c;它允许在 Spring 应用程序中发布和监听事件。这种机制的主要目的是为了实现解耦&#…

FineBI报表页面大屏小屏自适应显示问题

大屏正常显示 显示正常 小屏BI自适应显示 存在遮挡字体情况 小屏浏览器缩放显示 等比缩放后显示正常

[开发语言][c++][python]:C++与Python中的赋值、浅拷贝与深拷贝

C与Python中的赋值、浅拷贝与深拷贝 1. Python中的赋值、浅拷贝、深拷贝2. C中的赋值、浅拷贝、深拷贝2.1 概念2.2 示例&#xff1a;从例子中理解1) 不可变对象的赋值、深拷贝、浅拷贝2) 可变对象的赋值、浅拷贝与深拷贝3) **可变对象深浅拷贝(外层、内层改变元素)** 写在前面&…

Ubuntu server配置ssh远程登录

使用如下命令进行安装 apt-get install ssh 安装好后启动 service ssh start 然后查看运行状态 然后用本机ping虚拟机 关闭本机和虚拟机防火墙 ufw disable 然后打开Xshell进行连接

删除的数据恢复

1回收站恢复 1.1回收站删除 新手删除是通过del键或者鼠标右键删除,这种删除是并不是真正的删除,而是放到了回收站 1.2回收站的数据恢复 回收站的数据,你要恢复那个直接右键还原即可,删除到回收站的数据并不能称得上是删除,回收站的本质也是一个文件夹,只不过是个特殊的文件…

少儿编程 2023年12月电子学会图形化编程等级考试Scratch二级真题解析(判断题)

2023年12月scratch编程等级考试二级真题 判断题(共10题,每题2分,共20分) 26、声音Medieval1的长度是9.68秒,运行下列程序1或程序2都能实现,播放声音2秒后,声音停止角色移动100步 答案:对 考点分析:考查积木综合使用,重点考查声音积木的使用 程序1中用的是等待播完…

系统存储架构升级分享 | 京东云技术团队

一、业务背景 系统业务功能&#xff1a;系统内部进行数据处理及整合, 对外部系统提供结果数据的初始化(写)及查询数据结果服务。 系统网络架构: 部署架构对切量上线的影响 - 内部管理系统上线对其他系统的读业务无影响分布式缓存可进行单独扩容, 与存储及查询功能升级无关通过…

掌握 Vue 响应式系统,让数据驱动视图(下)

&#x1f90d; 前端开发工程师&#xff08;主业&#xff09;、技术博主&#xff08;副业&#xff09;、已过CET6 &#x1f368; 阿珊和她的猫_CSDN个人主页 &#x1f560; 牛客高级专题作者、在牛客打造高质量专栏《前端面试必备》 &#x1f35a; 蓝桥云课签约作者、已在蓝桥云…

分析一个项目(微信小程序篇)三

目录 接下来分析接口方面&#xff1a; home接口&#xff1a; categories接口&#xff1a; details接口&#xff1a; login接口&#xff1a; 分析一个项目讲究的是如何进行对项目的解析分解&#xff0c;进一步了解项目的整体结构&#xff0c;熟悉项目的结构&#xff0c;能够…

impala元数据自动刷新

一.操作步骤 进入CM界面 > Hive > 配置 > 搜索 启用数据库中的存储通知(英文界面搜索&#xff1a;Enable Stored Notifications in Database)&#xff0c;并且勾选&#xff0c;注意一定要勾选&#xff0c;配置后面的配置不生效。数据库通知的保留时间默认为2天&#…

2-认识小程序项目

基本结构 myapp├─miniprogram┊ └──pages┊ ┊ └──index┊ ┊ ┊ ├──index.json┊ ┊ ┊ ├──index.ts┊ ┊ ┊ ├──index.wxml┊ ┊ ┊ └──index.wxss┊ ┊ └──logs┊ ┊ ├──index.json┊ ┊ ├──index.ts┊ ┊ ├…

评论转换输出 - 华为OD统一考试

OD统一考试 分值&#xff1a; 200分 题解&#xff1a; Java / Python / C 题目描述 在一个博客网站上&#xff0c;每篇博客都有评论。每一条评论都是一个非空英文字母字符串。 评论具有树状结构&#xff0c;除了根评论外&#xff0c;每个评论都有一个父评论。当评论保存时&am…

VMware workstation安装MX-23.1虚拟机并配置网络

VMware workstation安装MX-23.1虚拟机并配置网络 MX Linux是基于Debian稳定分支的面向桌面的Linux发行&#xff0c;采用Xfce作为缺省桌面&#xff0c;是一份中量级操作系统。该文档适用于在VMware workstation平台安装MX-23.1虚拟机。 1.安装准备 1.1安装平台 Windows 11 …

个人网站制作 Part 3 用JS添加高级交互(表单验证、动态内容更新) | Web开发项目

文章目录 &#x1f469;‍&#x1f4bb; 基础Web开发练手项目系列&#xff1a;个人网站制作&#x1f680; 使用JavaScript进行交互&#x1f528;表单验证&#x1f527;步骤 1: 添加JavaScript文件&#x1f527;步骤 2: 更新表单HTML &#x1f528;动态内容更新&#x1f527;步骤…

用js做个转盘

样式 <style>.wheel {position: relative;width: 400px;height: 400px;border: 1px solid black;border-radius: 50%;overflow: hidden;margin: auto;}.slice {position: absolute;left: 0;top: 0;width: 0;height: 0;border: 200px solid red;/* border-width: 100px 10…

Python - 操作 docx

文章目录 使用库 : python-docx 官方文档&#xff1a;https://python-docx.readthedocs.io 安装 pip install python-docx提取 docx from docx import Documentdoc Document(file_path) text "" for para in doc.paragraphs:text para.text "\n"创建…