欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

elasticsearch springboot 实现分词搜索

程序员文章站 2022-07-05 18:11:15
...

实现分词搜索之前必须保证您的springboot 已经连接上了你的elasticsearch

这里展示下我的配置信息和pom文件

application.yml

spring: 
  data: 
    elasticsearch: 
    ####集群名称
      cluster-name: elasticsearch
    ####地址 
      cluster-nodes: 47.107.91.27:9300
<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>2.0.0.RELEASE</version>
		<relativePath /> <!-- lookup parent from repository -->
	</parent>
	<dependencies>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-web</artifactId>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-data-elasticsearch</artifactId>
		</dependency>
		<dependency>
			<groupId>org.projectlombok</groupId>
			<artifactId>lombok</artifactId>
		</dependency>
		<dependency>
			<groupId>com.google.collections</groupId>
			<artifactId>google-collections</artifactId>
			<version>1.0-rc2</version>
		</dependency>
		<!-- springboot整合freemarker -->
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-freemarker</artifactId>
		</dependency>
</dependencies>

首先创建实体类

@Document(indexName = "***", type = "***")
@Data
public class UserEntity {
	@Id
	private String id;
	private String name;
	private int sex;
	private int age;
}

@Data
是设置get set方法 插件
indexName type 设置好即可

创建对应的Dao层 记住继承的是ElasticsearchRepository 只有这个类是分词查找

@Component
public interface UserReposiory extends ElasticsearchRepository<UserEntity, String> {
	Iterable<UserEntity> findByNameContaining(String name);
}
@RestController
public class EsController {

	@Autowired
	private UserReposiory userReposiory;
	
	@RequestMapping("/text")
	public List<UserEntity> search(String name,
			@PageableDefault(page = 0, value = 2) Pageable pageable) {
		// 1.创建查询对象
		BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();
			MatchQueryBuilder matchQuery = QueryBuilders.matchQuery("name", name);
			boolQuery.must(matchQuery);
		// 2.调用查询接口
		Iterable<UserEntity> search = userReposiory.search(boolQuery, pageable);
		// 3.将迭代器转换为集合
		return Lists.newArrayList(search);
	}
}

启动类

@SpringBootApplication
@EnableElasticsearchRepositories(basePackages = "com.cc.reposiory")
public class AppEs {
	public static void main(String[] args) {
		SpringApplication.run(AppEs.class, args);
	}
}

得到结果
可以看到 springboot 蚂蚁 被分为2个关键词 一个是springboot 一个是蚂蚁(使用ki分词器,如果是默认的分词器,中文会每个字都会作为一个分词)
springboot陈晨因为 springboot 关键词而搜出来了
elasticsearch springboot 实现分词搜索