spring-boot 2.3.x 整合elasticsearch
文章目录
本地项目的基础环境
环境 | 版本 |
---|---|
jdk | 1.8.0_201 |
maven | 3.6.0 |
Spring-boot | 2.3.3.RELEASE |
elasticsearch | 7.8.0 |
1、elasticsearch的安装(docker形式)
这里使用docker,做一个快速的单机版本安装,需要更详细的其他形式的安装,可以查看其他的相关资料或者官网地址
《docker、docker-compose 下安装elasticsearch、IK分词器》
《docker、docker-compose 下安装kibana》
1.1、docker-compose.yml
version: '3.1'
services:
es01:
image: docker.elastic.co/elasticsearch/elasticsearch:7.8.0
container_name: es01
environment:
- discovery.type=single-node
volumes:
- /Users/liqi/docker-compose/elasticsearch/data:/usr/share/elasticsearch/data
- /Users/liqi/docker-compose/elasticsearch/plugins:/usr/share/elasticsearch/plugins
- /Users/liqi/docker-compose/elasticsearch/config:/usr/share/elasticsearch/config
ports:
- 9200:9200
- 9300:9300
2、构建一个elasticsearch的项目badger-spring-boot-elasticsearch
主要是导入spring-boot-starter-data-elasticsearch
的包;
<?xml version="1.0"?>
<project xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"
xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.3.3.RELEASE</version>
<relativePath /> <!-- lookup parent from repository -->
</parent>
<groupId>com.badger</groupId>
<artifactId>badger-spring-boot-elasticsearch</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>badger-spring-boot-elasticsearch</name>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<java.version>1.8</java.version>
<maven-jar-plugin.version>3.1.1</maven-jar-plugin.version>
</properties>
<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.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.76</version>
</dependency>
</dependencies>
<build>
<plugins>
<!-- 打包插件 -->
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
3.1、定义yml配置文件
spring:
elasticsearch:
rest:
uris:
- http://127.0.0.1:9200
org.springframework.boot.autoconfigure.elasticsearch.ElasticsearchRestClientProperties.class
具体更可以参看配置类;
配置属性为
/**
* Configuration properties for Elasticsearch REST clients.
*
* @author Brian Clozel
* @since 2.1.0
*/
@ConfigurationProperties(prefix = "spring.elasticsearch.rest")
public class ElasticsearchRestClientProperties {
/**
* Comma-separated list of the Elasticsearch instances to use.
*/
private List<String> uris = new ArrayList<>(Collections.singletonList("http://localhost:9200"));
/**
* Credentials username.
*/
private String username;
/**
* Credentials password.
*/
private String password;
/**
* Connection timeout. 链接超时
*/
private Duration connectionTimeout = Duration.ofSeconds(1);
/**
* Read timeout. 链接后,返回数据的读超时
*/
private Duration readTimeout = Duration.ofSeconds(30);
3.2、定义es的对应的实体
/**
* es存库的实体
* @author liqi
* @data 2022年5月16日 下午4:20:33
*/
@Document(indexName = "test_product", shards = 3)
@Data
public class SearchProduct implements Serializable {
private static final long serialVersionUID = -6629478619791342054L;
/**主键*/
@Id
private Integer id;
/**skuId*/
@Field(type = FieldType.Keyword)
private String skuId;
/**名称1*/
@Field(type = FieldType.Text, analyzer = "ik_smart")
private String name;
/**价格*/
private Double price;
}
@Id
注解:必须有 id,这里的 id 是全局唯一的标识,等同于 es 中的"_id";
@Field
注解:
- type : 字段数据类型
- analyzer : 分词器类型
- index : 是否索引(默认:true)
- Keyword : 短语,不进行分词
3.3、定义es的CrudRepository
/**
* es dao
* @author liqi
*
*/
public interface SearchProductDao extends ElasticsearchRepository<SearchProduct, Integer> {
}
可以看到,自定义的SearchProductDao.class
继承了ElasticsearchRepository<T, ID>.class
/**
* @param <T>
* @param <ID>
* @author Rizwan Idrees
* @author Mohsin Husen
* @author Sascha Woo
* @author Murali Chevuri
* @author Peter-Josef Meisch
*/
@NoRepositoryBean
public interface ElasticsearchRepository<T, ID> extends PagingAndSortingRepository<T, ID> {
/**
* @deprecated since 4.0, use {@link #save(Object)} instead
*/
@Deprecated
default <S extends T> S index(S entity) {
return save(entity);
}
/**
* This method is intended to be used when many single inserts must be made that cannot be aggregated to be inserted
* with {@link #saveAll(Iterable)}. This might lead to a temporary inconsistent state until {@link #refresh()} is
* called.
*
* @deprecated since 4.0, use a custom repository implementation instead
*/
@Deprecated
<S extends T> S indexWithoutRefresh(S entity);
/**
* @deprecated since 4.0, use standard repository method naming or @{@link Query} annotated methods, or
* {@link org.springframework.data.elasticsearch.core.ElasticsearchOperations}.
*/
Iterable<T> search(QueryBuilder query);
/**
* @deprecated since 4.0, use standard repository method naming or @{@link Query} annotated methods, or
* {@link org.springframework.data.elasticsearch.core.ElasticsearchOperations}.
*/
Page<T> search(QueryBuilder query, Pageable pageable);
/**
* @deprecated since 4.0, use standard repository method naming or @{@link Query} annotated methods, or
* {@link org.springframework.data.elasticsearch.core.ElasticsearchOperations}.
*/
Page<T> search(Query searchQuery);
/**
* Search for similar entities using a morelikethis query
*
* @param entity the entity for which similar documents should be searched, must not be {@literal null}
* @param fields
* @param pageable , must not be {@literal null}
* @return
*/
Page<T> searchSimilar(T entity, @Nullable String[] fields, Pageable pageable);
/**
* @deprecated since 4.0, use {@link IndexOperations#refresh(Class)} instead. Repository methods should call refresh
* in their implementation.
*/
@Deprecated
void refresh();
}
1、其中泛型<T>
表示使用的实体;
2、泛型<ID>
表示的主键的类型;
3、ElasticsearchRepository<T, ID>.class
继承了PagingAndSortingRepository<T, ID>
PagingAndSortingRepositor.class类是在spring-data
包下了,具体怎么使用,就不再详细解释这个标准了;
3.4、主启动类
@SpringBootApplication
public class ElasticsearchApplicaltion {
public static void main(String[] args) throws Exception {
SpringApplication.run(ElasticsearchApplicaltion.class, args);
}
}
4、测试代码
4.1、查看当前es的索引
GET _cat/indices?v
可以看到,没有我们实体上的索引test_product
,只有之前的我测试的product
;
@RunWith(SpringRunner.class)
@SpringBootTest(classes = { ElasticsearchApplicaltion.class })
public class AppTest {
@Autowired
SearchProductDao searchProductDao;
@Test
public void save() {
List<SearchProduct> list = new ArrayList<SearchProduct>();
String names = "中天\n" + "敏杨\n" + "名爵尔\n" + "万宝龙\n" + "万宝龙\n" + "巴黎水";
String[] split = names.split("\n");
for (int i = 0; i < split.length; i++) {
SearchProduct searchProduct = new SearchProduct();
searchProduct.setId(i + 1);
searchProduct.setName(split[i]);
searchProduct.setSkuId("sku" + split[i]);
searchProduct.setPrice(i + 0.1D);
list.add(searchProduct);
}
searchProductDao.saveAll(list);
}
@Test
public void search() {
BoolQueryBuilder builder = QueryBuilders.boolQuery();
// 搜索关键词
builder.must(QueryBuilders.matchQuery("name", "中天"));
Iterable<SearchProduct> search = searchProductDao.search(builder);
for (SearchProduct searchProduct : search) {
System.out.println(JSON.toJSONString(searchProduct));
}
}
}
《docker、docker-compose 下安装elasticsearch、IK分词器》
《docker、docker-compose 下安装kibana》
详细代码也可以参看《码云》