文章目录
Spring Boot整合ES
官方文档:https://docs.spring.io/spring-data/elasticsearch/docs/current/reference/html/#new-features.4-4-0
版本选择
Elasticsearch 7.17.3 对应依赖 Spring Data Elasticsearch 4.4.x,对应springboot版本2.7.x
引入依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-elasticsearch</artifactId>
</dependency>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<java.version>1.8</java.version>
<spring-boot.version>2.7.13</spring-boot.version>
<lombok.version>1.18.16</lombok.version>
</properties>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>${spring-boot.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>${lombok.version}</version>
</dependency>
</dependencies>
</dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<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>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
yum配置
spring:
elasticsearch:
uris: http://localhost:9200
connection-timeout: 3s
创建实体
@Document(indexName = "employees")
指定索引名,注意这里@Document是es包下的注解,不要导入错了
Field
指定字段类型以及分词器,它是es包下的注解,不要导入错了
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.data.annotation.Id;
import org.springframework.data.elasticsearch.annotations.Document;
import org.springframework.data.elasticsearch.annotations.Field;
import org.springframework.data.elasticsearch.annotations.FieldType;
/**
* @Description: 索引为sys_user的实体
* @Author 胡尚
* @Date: 2024/8/11 17:00
*/
@Data
@AllArgsConstructor
@NoArgsConstructor
@Document(indexName = "sys_user")
public class UserEntity {
@Id
private Long id;
@Field(type = FieldType.Keyword)
private String name;
// @Field(index = false) 也可以指定不要创建索引
private int sex;
private int age;
@Field(type = FieldType.Text, analyzer = "ik_max_word")
private String address;
private String remark;
}
实现ElasticsearchRepository
该方式了解即可,一般都是使用的ElasticsearchRestTemplate对象操作
该接口是框架封装的用于操作Elastsearch的高级接口
import com.hs.es.entity.UserEntity;
import org.springframework.data.elasticsearch.repository.ElasticsearchRepository;
import org.springframework.stereotype.Repository;
import java.util.List;
/**
* @Description: 使用 实现ElasticsearchRepository 方式进行测试
* @Author 胡尚
* @Date: 2024/8/11 17:10
*/
@Repository
public interface UserRepository extends ElasticsearchRepository<UserEntity, Long> {
// 因为我实体类中字段名为name,所以这里方法名必须是ByName,不然就会报错,
List<UserEntity> findByName(String name);
}
我实体类使用username字段名报错信息如下图所示
测试
import com.hs.es.entity.UserEntity;
import com.hs.es.mapper.UserRepository;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import java.util.List;
import java.util.Optional;
/**
* @Description: 测试类
* @Author 胡尚
* @Date: 2024/8/11 17:13
*/
@SpringBootTest
@RunWith(SpringRunner.class)
public class ElasticsearchTest {
@Autowired
UserRepository userRepository;
@Test
public void testDocument(){
UserEntity user = new UserEntity(1L, "hs666", 1, 24, "长沙麓谷", "java architect");
// 插入文档
userRepository.save(user);
// 根据id查询
Optional<UserEntity> userOptional = userRepository.findById(1L);
System.out.println(userOptional.get());
//根据name查询
List<UserEntity> hsUser = userRepository.findByName("hs666");
System.out.println(hsUser.get(0));
}
}
使用ElasticsearchRestTemplate
@Autowired
ElasticsearchRestTemplate elasticsearchRestTemplate;
索引操作
import lombok.extern.slf4j.Slf4j;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;
import org.springframework.data.elasticsearch.core.IndexOperations;
import org.springframework.data.elasticsearch.core.mapping.IndexCoordinates;
import org.springframework.test.context.junit4.SpringRunner;
/**
* @Description: es测试类
* @Author 胡尚
* @Date: 2024/8/11 17:30
*/
@Slf4j
@SpringBootTest
@RunWith(SpringRunner.class)
public class EsTest {
@Autowired
ElasticsearchRestTemplate restTemplate;
// 创建索引
@Test
public void testCrateIndex(){
IndexOperations employeeIndex = restTemplate.indexOps(IndexCoordinates.of("employee_index"));
if (employeeIndex.exists()){
log.info("索引已存在");
}else {
log.info("创建索引");
employeeIndex.create();
}
}
// 删除索引
@Test
public void testDeleteIndex(){
IndexOperations employeeIndex = restTemplate.indexOps(IndexCoordinates.of("employee_index"));
employeeIndex.delete();
}
}
当然也可以把我们之前创建的User实体类也利用上,可以发现,创建的index的mapping下只有我们加了@Field
的字段信息
@Test
public void testCrateIndex2(){
IndexOperations userIndex = restTemplate.indexOps(IndexCoordinates.of("sys_user"));
// 调用createMapping()方法
userIndex.createMapping(UserEntity.class);
}
文档操作
import com.alibaba.fastjson2.JSON;
import com.hs.es.entity.UserEntity;
import lombok.extern.slf4j.Slf4j;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;
import org.springframework.data.elasticsearch.core.IndexOperations;
import org.springframework.data.elasticsearch.core.mapping.IndexCoordinates;
import org.springframework.data.elasticsearch.core.query.IndexQuery;
import org.springframework.test.context.junit4.SpringRunner;
import java.util.ArrayList;
import java.util.List;
/**
* @Description: es测试类
* @Author 胡尚
* @Date: 2024/8/11 17:30
*/
@Slf4j
@SpringBootTest
@RunWith(SpringRunner.class)
public class EsTest {
@Autowired
ElasticsearchRestTemplate restTemplate;
/**
* 批量插入文档
*/
@Test
public void testInsertDocumentBatch(){
List<UserEntity> userEntityList = new ArrayList<>();
userEntityList.add(new UserEntity(1L,"张三",1,25,"广州天河公园","java developer"));
userEntityList.add(new UserEntity(2L,"李四",1,28,"广州荔湾大厦","java assistant"));
userEntityList.add(new UserEntity(3L,"小红",0,26,"广州白云山公园","php developer"));
List<IndexQuery> indexQueries = new ArrayList<>();
for (UserEntity userEntity : userEntityList) {
// 封装id与数据
IndexQuery indexQuery = new IndexQuery();
indexQuery.setId(String.valueOf(userEntity.getId()));
indexQuery.setSource(JSON.toJSONString(userEntity));
indexQueries.add(indexQuery);
}
// 批量插入
restTemplate.bulkIndex(indexQueries, UserEntity.class);
}
}
插入的数据如下
package com.hs.es;
import com.alibaba.fastjson2.JSON;
import com.hs.es.entity.UserEntity;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.sort.SortBuilders;
import org.elasticsearch.search.sort.SortOrder;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;
import org.springframework.data.elasticsearch.core.IndexOperations;
import org.springframework.data.elasticsearch.core.SearchHit;
import org.springframework.data.elasticsearch.core.SearchHits;
import org.springframework.data.elasticsearch.core.mapping.IndexCoordinates;
import org.springframework.data.elasticsearch.core.query.IndexQuery;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.test.context.junit4.SpringRunner;
import java.util.ArrayList;
import java.util.List;
/**
* @Description: es测试类
* @Author 胡尚
* @Date: 2024/8/11 17:30
*/
@Slf4j
@SpringBootTest
@RunWith(SpringRunner.class)
public class EsTest {
@Autowired
ElasticsearchRestTemplate restTemplate;
/**
* 查询文档
*/
@Test
public void testQueryDocument(){
NativeSearchQueryBuilder builder = new NativeSearchQueryBuilder();
// 查询
builder.withQuery(QueryBuilders.matchQuery("address", "公园"));
// 设置分页信息
builder.withPageable(PageRequest.of(0,5));
// 设置排序
builder.withSorts(SortBuilders.fieldSort("age").order(SortOrder.DESC));
SearchHits<UserEntity> searchHits = restTemplate.search(builder.build(), UserEntity.class);
for (SearchHit<UserEntity> searchHit : searchHits) {
System.out.println(JSON.toJSON(searchHit));
System.out.println(searchHit.getContent());
}
}
}
一个SearchHit对象保存的信息如下
{
"content": {
"address": "广州白云山公园",
"age": 26,
"id": 3,
"name": "小红",
"remark": "php developer",
"sex": 0
},
"highlightFields": {
},
"id": "3",
"index": "sys_user",
"innerHits": {
},
"matchedQueries": [
],
"score": null,
"sortValues": [
26
]
}
标签:SpringBoot,boot,springframework,ElasticSearch,elasticsearch,整合,org,import,data
From: https://blog.csdn.net/qq_44027353/article/details/141109731