spring boot 接入Elasticsearch 模糊查询例子如何编写
时间: 2024-01-30 14:01:33 浏览: 76
1. 添加依赖
在 pom.xml 文件中添加 Elasticsearch 相关依赖:
```
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-elasticsearch</artifactId>
</dependency>
```
2. 配置 Elasticsearch
在 application.properties 配置文件中添加 Elasticsearch 的配置:
```
spring.data.elasticsearch.cluster-name=my-cluster-name
spring.data.elasticsearch.cluster-nodes=192.168.1.1:9300,192.168.1.2:9300
```
3. 编写实体类
创建一个实体类,用于映射 Elasticsearch 中的文档:
```
@Document(indexName = "my-index", type = "my-type")
public class MyEntity {
@Id
private String id;
private String name;
private String description;
// getter and setter
}
```
4. 创建 Elasticsearch Repository
创建一个 Elasticsearch Repository 接口,继承 ElasticsearchRepository 接口,用于操作 Elasticsearch:
```
public interface MyEntityRepository extends ElasticsearchRepository<MyEntity, String> {
List<MyEntity> findByNameLike(String name);
}
```
5. 实现模糊查询
在自定义的 Repository 接口中添加一个方法,用于实现模糊查询:
```
public interface MyEntityRepositoryCustom {
List<MyEntity> search(String keyword);
}
public class MyEntityRepositoryImpl implements MyEntityRepositoryCustom {
@Autowired
private ElasticsearchTemplate elasticsearchTemplate;
@Override
public List<MyEntity> search(String keyword) {
QueryBuilder queryBuilder = QueryBuilders.boolQuery()
.should(QueryBuilders.matchQuery("name", keyword))
.should(QueryBuilders.matchQuery("description", keyword));
SearchQuery searchQuery = new NativeSearchQueryBuilder()
.withQuery(queryBuilder)
.build();
return elasticsearchTemplate.queryForList(searchQuery, MyEntity.class);
}
}
```
6. 测试
在测试类中使用 MyEntityRepository 中的方法进行测试:
```
@RunWith(SpringRunner.class)
@SpringBootTest
public class MyEntityRepositoryTest {
@Autowired
private MyEntityRepository myEntityRepository;
@Test
public void testSearch() {
List<MyEntity> result = myEntityRepository.search("spring boot");
assertThat(result.size(), equalTo(1));
assertThat(result.get(0).getName(), equalTo("Spring Boot"));
}
}
```
这样就可以实现在 Spring Boot 中接入 Elasticsearch 并进行模糊查询了。
阅读全文