首页 > 其他分享 >springboot 集成elasticsearch Ik分词

springboot 集成elasticsearch Ik分词

时间:2024-03-28 10:36:38浏览次数:30  
标签:index return springboot param public Ik elasticsearch id String

前提是我们elasticsearch 服务已经集成了IK分词,具体集成下载对应的elasticsearch IK分词插件,在es插件包下创建IK文件夹,将下载好的IK包上传上去解压后重启es
1、pom引入


co.elastic.clients
elasticsearch-java
7.16.2


jakarta.json
jakarta.json-api
2.0.1


org.springframework.boot
spring-boot-starter-data-elasticsearch

2、配置config类
@Configuration
public class RestClientConfig {

@Value("${elasticsearch.ip}")
private String ip;

@Bean
public ElasticsearchClient elasticsearchClient() {
	ElasticsearchClient client;
	// Create the low-level client
	RestClient restClient = RestClient.builder(this.getElasticSearchHttpHosts()).build();
	// Create the transport with a Jackson mapper
	ElasticsearchTransport transport = new RestClientTransport(restClient, new JacksonJsonpMapper());
	// And create the API client
	client = new ElasticsearchClient(transport);
	return client;
}

/**
 * ElasticSearch 连接地址
 * 多个逗号分隔
 * 示例:127.0.0.1:9201,127.0.0.1:9202,127.0.0.1:9203
 */
private HttpHost[] getElasticSearchHttpHosts() {
	String[] hosts = ip.split(",");
	HttpHost[] httpHosts = new HttpHost[hosts.length];
	for (int i = 0; i < httpHosts.length; i++) {
		String host = hosts[i];
		httpHosts[i] = new HttpHost(host.split(":")[0], Integer.parseInt(host.split(":")[1]));
	}
	return httpHosts;
}

}
3、创建service
/**

  • 自定义es查询接口
    /
    public interface IBizElasticsearchService {
    /
    *

    • 判断索引是否存在
    • @param index 索引
    • @return boolean
      */
      public boolean existsIndex(String index);

    /**

    • 创建索引
    • @param index 索引
    • @param aliasename aliasename
    • @return boolean
      */
      public boolean createIndex(String index, String aliasename, int numOfShards, Map<String, Property> properties);

    /**

    • 删除索引
    • @param indexList indexList
    • @return boolean
      */
      public boolean deleteIndex(List indexList);

    /**

    • 判断文档是否存在
    • @param index index
    • @param id id
    • @return boolean
      */
      public boolean existsDocument(String index, String id, Class clazz);

    /**

    • 保存文档
    • 如果文档存在则更新文档
    • @param index index
    • @param id id
    • @param qa qa
    • @return IndexResponse
      */
      public IndexResponse saveOrUpdateDocument(String index, String id, T qa);

    /**

    • 不指定IO保存文档
    • @param index 索引
    • @param qa 数据
    • @return IndexResponse
      */
      public IndexResponse saveOrUpdateDocument(String index, T qa);

    /**

    • 根据id获取文档
    • @param index index
    • @param id id
    • @param clazz clazz
    • @return T
      */
      public T getById(String index, String id, Class clazz);

    /**

    • 根据id列表获取文档
    • @param index index
    • @param idList id
    • @param clazz clazz
    • @return List
      */
      public List getByIdList(String index, List idList, Class clazz);

    /**

    • 分页查询
    • @param index index
    • @param pageNo pageNo
    • @param pageSize pageSize
    • @param clazz clazz
    • @return HitsMetadata
      */
      public HitsMetadata searchByPages(String index, Integer pageNo, Integer pageSize, Class clazz, SearchRequest searchRequest);

    /**

    • 根据id删除文档
    • @param id id
      */
      public boolean deleteById(String index, String id);

    /**

    • 查询list
    • @param clazz
    • @param searchRequest
    • @return
      */
      HitsMetadata searchList(Class clazz, SearchRequest searchRequest);
      }
      4、serviceImpl

@Service
@Slf4j
public class BizElasticsearchServiceImpl implements IBizElasticsearchService {

@Autowired
private ElasticsearchClient client;



@Autowired
public void setClient(ElasticsearchClient client) {
	this.client = client;
}

public boolean existsIndex(String index) {
	try {
		ExistsRequest existsRequest = new ExistsRequest.Builder().index(index).build();
		BooleanResponse response = client.indices().exists(existsRequest);
		return response.value();
	} catch (IOException e) {
		log.error("There is an error while getting index", e);
	}
	return false;
}

@Override
public boolean createIndex(String indexName, String aliasesName, int numOfShards, Map<String, Property> properties) {
	try {
		TypeMapping typeMapping = new TypeMapping.Builder().properties(properties).build();
		// 我这里需要用到ik分词器,所以setting就写死了
		IndexSettings indexSettings = new IndexSettings.Builder().numberOfShards(String.valueOf(numOfShards))
			.analysis(q->q.analyzer("ik_max_tokenizer",q1->q1.custom(a->a.tokenizer("ik_max_word")))).build();
		CreateIndexRequest createIndexRequest = new CreateIndexRequest.Builder()
			.index(indexName)
			.aliases(aliasesName, new Alias.Builder().isWriteIndex(true).build())
			.mappings(typeMapping)
			.settings(indexSettings)
			.build();
		CreateIndexResponse response = client.indices().create(createIndexRequest);
		return response.acknowledged();
	} catch (IOException e) {
		log.error("There is an error while creating index", e);
	}
	return false;
}

@Override
public boolean deleteIndex(List<String> indexList) {
	try {
		DeleteIndexRequest deleteIndexRequest = new DeleteIndexRequest.Builder().index(indexList).build();
		DeleteIndexResponse response = client.indices().delete(deleteIndexRequest);
		return response.acknowledged();
	} catch (IOException e) {
		log.error("There is an error while deleting index", e);
	}
	return false;
}

@Override
public boolean existsDocument(String index, String id, Class<T> clazz) {
	try {
		GetRequest getRequest = new GetRequest.Builder().index(index).id(id).build();
		GetResponse<T> getResponse = client.get(getRequest, clazz);
		return getResponse.found();
	} catch (IOException e) {
		log.error("There is an error while judging if the document exists", e);
	}
	return false;
}

@Override
public IndexResponse saveOrUpdateDocument(String index, String id, T t) {
	try {
		IndexRequest<T> indexRequest = new IndexRequest.Builder<T>().index(index).id(id).document(t).build();
		return client.index(indexRequest);
	} catch (IOException e) {
		log.error("There is an error while saving the document", e);
	}

	return null;
}

@Override
public IndexResponse saveOrUpdateDocument(String index, T t) {
	try {
		IndexRequest<T> indexRequest = new IndexRequest.Builder<T>().index(index).document(t).build();
		return client.index(indexRequest);
	} catch (IOException e) {
		log.error("There is an error while saving the document", e);
	}
	return null;
}

@Override
public T getById(String index, String id,  Class<T> clazz) {
	try {
		GetRequest getRequest = new GetRequest.Builder().index(index).id(id).build();
		GetResponse<T> getResponse = client.get(getRequest, clazz);
		return getResponse.source();
	} catch (IOException e) {
		log.error("There is an error while getting the document", e);
	}
	return null;
}

@Override
public List<T> getByIdList(String index, List<String> idList, Class<T> clazz) {
	try {
		List<T> tList = new ArrayList<>(idList.size());
		for (String id : idList) {
			tList.add(client.get(new GetRequest.Builder().index(index).id(id).build(), clazz).source());
		}
		return tList;
	} catch (IOException e) {
		log.error("There is an error while getting the document list", e);
	}
	return null;
}

@Override
public HitsMetadata<T> searchByPages(String index, Integer pageNo, Integer pageSize, Class<T> clazz,SearchRequest searchRequest) {
	try {
		SearchResponse<T> searchResponse = client.search(searchRequest, clazz);
		return searchResponse.hits();
	} catch (IOException e) {
		log.error("There is an error while searching by pages", e);
	}
	return null;
}
@Override
public HitsMetadata<T> searchList(Class<T> clazz,SearchRequest searchRequest) {
	try {
		SearchResponse<T> searchResponse = client.search(searchRequest, clazz);
		return searchResponse.hits();
	} catch (IOException e) {
		log.error("There is an error while searching by list", e);
	}
	return null;
}




public boolean deleteById(String index, String id) {
	try {
		DeleteRequest deleteRequest = new DeleteRequest.Builder().index(index).id(id).build();
		DeleteResponse deleteResponse = client.delete(deleteRequest);
		return "deleted".equals(deleteResponse.result().jsonValue());
	} catch (IOException e) {
		log.error("There is an error while deleting id document", e);
	}
	return false;
}

}
这里主要讲下我们对那些字段分词,我们调用createIndex,传入Map<String, Property> properties,如下是我们对title和content字段进行IK分词:
Map<String,Property> map = new HashMap<>();
Property titleProperty = Property.of(pBuilder -> pBuilder.text(tBuilder -> tBuilder.analyzer("ik_max_word").searchAnalyzer("ik_max_word")));
map.put("title",titleProperty);
Property contentProperty = Property.of(pBuilder -> pBuilder.text(tBuilder -> tBuilder.analyzer("ik_max_word").searchAnalyzer("ik_max_word")));
map.put("content",contentProperty);
return R.data(bizElasticsearchService.createIndex(indexName,indexName+"_aliases",2,map));

标签:index,return,springboot,param,public,Ik,elasticsearch,id,String
From: https://www.cnblogs.com/xiaokangk/p/18100984

相关文章

  • springboot223基于springboot的信息技术知识竞赛系统的设计与实现
    具体演示视频链接:https://pan.baidu.com/s/1epOAnmfyRpfuI3eBR13WDA?pwd=8888毕业设计(论文)信息技术知识赛系统设计与实现摘要传统办法管理信息首先需要花费的时间比较多,其次数据出错率比较高,而且对错误的数据进行更改也比较困难,最后,检索数据费事费力。因此,在计算机......
  • 基于SpringBoot+Vue的在线家具商城毕业设计
    文章目录前言详细视频演示具体实现截图技术栈后端框架SpringBoot前端框架Vue持久层框架MyBaitsPlus系统测试系统测试目的系统功能测试系统测试结论为什么选择我代码参考数据库参考源码获取前言......
  • 基于SpringBoot+Vue的新冠病毒密接者跟踪系统毕业设计
    文章目录前言详细视频演示具体实现截图技术栈后端框架SpringBoot前端框架Vue持久层框架MyBaitsPlus系统测试系统测试目的系统功能测试系统测试结论为什么选择我代码参考数据库参考源码获取前言......
  • springboot/ssm招聘系统Java企业在线招聘系统web校园大学生招聘平台
    springboot/ssm招聘系统Java企业在线招聘系统web校园大学生招聘平台基于springboot(可改ssm)+vue项目开发语言:Java框架:springboot/可改ssm+vueJDK版本:JDK1.8(或11)服务器:tomcatpackagecom.controller;importjava.text.SimpleDateFormat;importjava.util.ArrayLi......
  • SpringBoot整合Redis:面试必考题-缓存击穿--逻辑过期解决
    ......
  • springboot关于注册条件相关内容
    核心注解为@Condition//如果配置文件中存在了指定信息,才会注入,否则不注入@ConditionalOnProperty(prefix="country",name={"name","system"})此时因为配置文件中没有指定信息,所以没有注入到ioc池中,Countrycountry=context.getBean(Country.class);所以在启动类中无法......
  • 基于java+springboot+vue实现的超市货品信息管理系统(文末源码+Lw+ppt)23-355
    摘 要随着世界经济信息化、全球化的到来和互联网的飞速发展,推动了各行业的改革。若想达到安全,快捷的目的,就需要拥有信息化的组织和管理模式,建立一套合理、动态的、交互友好的、高效的超市货品信息管理系统。当前的信息管理存在工作效率低,工作繁杂等问题,基于信息化的超市货品......
  • 基于java+springboot+vue实现的校园二手交易系统(文末源码+Lw+ppt)23-336
    摘 要自从新冠疫情爆发以来,各个线下实体越来越难做,线下购物的人也越来越少,随之带来的是一些不必要的浪费,尤其是即将毕业的大学生,各种用品不方便携带走导致被遗弃,造成大量的浪费。本系统目的就是让毕业生的二手物品有一定的价值,并且在疫情环境下做到零接触买卖,更加安全。在......
  • 基于java+springboot+vue实现的超市管理系统(文末源码+Lw+ppt)23-354
    摘 要系统根据现有的管理模块进行开发和扩展,采用面向对象的开发的思想和结构化的开发方法对超市管理的现状进行系统调查。采用结构化的分析设计,该方法要求结合一定的图表,在模块化的基础上进行系统的开发工作。在设计中采用“自下而上”的思想,在超市管理系统实现了员工信息、......
  • 基于java+springboot+vue实现的校园二手交易系统(文末源码+Lw+ppt)23-336
     摘 要自从新冠疫情爆发以来,各个线下实体越来越难做,线下购物的人也越来越少,随之带来的是一些不必要的浪费,尤其是即将毕业的大学生,各种用品不方便携带走导致被遗弃,造成大量的浪费。本系统目的就是让毕业生的二手物品有一定的价值,并且在疫情环境下做到零接触买卖,更加安全。......