springboot 整合Elasticsearch7.6.2

版本对应

本次整合的elasticsearch版本为7.6.2,对应springboot版本号为2.3.3

pom文件

pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
	<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.sunyuqi</groupId>
	<artifactId>springboot-elasticsearch</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<name>springboot-elasticsearch</name>
	<description>Demo project for Spring Boot</description>

	<properties>
		<java.version>9</java.version>
	</properties>

	<dependencies>
		<dependency>
			<groupId>org.elasticsearch.client</groupId>
			<artifactId>elasticsearch-rest-high-level-client</artifactId>
			<version>7.6.2</version>
		</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-web</artifactId>
		</dependency>

		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-test</artifactId>
			<scope>test</scope>
		</dependency>
	</dependencies>

	<build>
		<plugins>
			<plugin>
				<groupId>org.springframework.boot</groupId>
				<artifactId>spring-boot-maven-plugin</artifactId>
			</plugin>
		</plugins>
	</build>
</project>

application.yml

spring: 
	elasticsearch:
		rest.uris: http://127.0.0.1:9200

实体类

package com.sunyuqi.es.entity;

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;

//索引库名为index_name,类型为article,分片为5,每片备份1片
@Document(indexName = "index_name", type = "article",shards = 5,replicas = 1)
public class Article {
    @Id
    @Field(type = FieldType.Long, store = true)
    private long id;
    @Field(type = FieldType.Text, store = true, analyzer = "ik_smart")
    private String title;
    @Field(type = FieldType.Text, store = true, analyzer = "ik_smart")
    private String content;

    public long getId() {
        return id;
    }

    public void setId(long id) {
        this.id = id;
    }

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public String getContent() {
        return content;
    }

    public void setContent(String content) {
        this.content = content;
    }

    @Override
    public String toString() {
        return "Article{" +
                "id=" + id +
                ", title='" + title + '\'' +
                ", content='" + content + '\'' +
                '}';
    }
}

ElasticsearchRepository接口

自定义接口需要继承ElasticsearchRepository接口,接口方法命名规则类似spring data jpa,无需实现具体接口方法

package com.sunyuqi.es.repositories;


import com.sunyuqi.es.entity.Article;
import org.springframework.data.domain.Pageable;
import org.springframework.data.elasticsearch.repository.ElasticsearchRepository;

import java.util.List;

public interface ArticleRepository extends ElasticsearchRepository<Article, Long> {
    List<Article> findByTitle(String title);
    List<Article> findByContent(String content);
    List<Article> findByTitleOrContent(String title, String content);
    List<Article> findByTitleOrContent(String title, String content, Pageable pageable);

}

springboot引导类

package com.sunyuqi;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class SpringbootElasticsearchApplication {

	public static void main(String[] args) {
		SpringApplication.run(SpringbootElasticsearchApplication.class, args);
	}

}

测试类

package com.sunyuqi;

import com.sunyuqi.es.entity.Article;
import com.sunyuqi.es.repositories.ArticleRepository;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.aggregations.metrics.ParsedAvg;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.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.domain.Pageable;
import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;
import org.springframework.data.elasticsearch.core.SearchHit;
import org.springframework.data.elasticsearch.core.SearchHits;
import org.springframework.data.elasticsearch.core.query.NativeSearchQuery;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.test.context.junit4.SpringRunner;

import java.util.List;

@RunWith(SpringRunner.class)
@SpringBootTest(classes = SpringbootElasticsearchApplication.class)
class SpringbootElasticsearchApplicationTests {

	@Autowired
	private ArticleRepository articleRepository;

	@Autowired
	private ElasticsearchRestTemplate template;

	//添加文档
	@Test
	public void addDocument() throws Exception {
		for (int i = 0; i <= 20; i++) {
			//创建一个Article对象
			Article article = new Article();
			article.setId(i);
			article.setTitle("测试的标题" + i);
			article.setContent("测试的内容"+i);
			//把文档写入索引库
			articleRepository.save(article);
		}
	}

	@Test
	public void deleteDocumentById() throws Exception {
		articleRepository.deleteById(1l);
		//全部删除
//		articleRepository.deleteAll();
	}

	//查询所有文档
	@Test
	public void findAll() throws Exception {
		Iterable<Article> articles = articleRepository.findAll();
        for (Article article : articles) {
            System.out.println(article);
        }
    }
    //根据ID查询
	@Test
	public void testFindById() throws Exception {
		Article article = template.get("14", Article.class);
		System.out.println(article);
	}
	//匹配标题,精准匹配
	@Test
	public void testFindByTitle() throws Exception {
		List<Article> list = articleRepository.findByTitle("标题");
		for (Article article : list) {
			System.out.println(article);
		}
	}
	//匹配标题或者内容
	@Test
	public void testFindByTitleOrContent() throws Exception {
		Pageable pageable = PageRequest.of(1, 5);
		List<Article> articles = articleRepository.findByTitleOrContent("maven", "内容", pageable);
		for (Article article : articles) {
			System.out.println(article);
		}
	}

	//分词查询
	@Test
	public void testNativeSearchQuery() throws Exception {
		//创建一个查询对象
		NativeSearchQuery query = new NativeSearchQueryBuilder()
				.withQuery(QueryBuilders.queryStringQuery("内容包含").defaultField("content"))
				.withPageable(PageRequest.of(0, 15))
				.build();
		//执行查询
		SearchHits<Article> search = template.search(query, Article.class);
		List<SearchHit<Article>> searchHits = search.getSearchHits();
		for (SearchHit<Article> searchHit : searchHits) {
			System.out.println(searchHit.getContent());
		}

		//获取聚合结果
		if (search.hasAggregations()) {
			ParsedAvg parsedAvg = search.getAggregations().get("avg_price");
			Assertions.assertNotNull(parsedAvg, "无聚合结果");
			System.out.println(parsedAvg.getValue());
		}
	}
}

添加文档时如果索引库不存在则会自动创建

  • 2
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
好的,下面是SpringBoot整合Elasticsearch的步骤: 1. 添加Elasticsearch的依赖 在pom.xml文件中添加以下依赖: ``` <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-elasticsearch</artifactId> </dependency> ``` 2. 配置Elasticsearch连接 在application.yml或application.properties中添加以下配置: ``` spring: data: elasticsearch: cluster-name: elasticsearch # Elasticsearch集群名称 cluster-nodes: 127.0.0.1:9300 # Elasticsearch连接地址 ``` 3. 创建Elasticsearch实体类 创建一个Java类,使用@Document注解标记为Elasticsearch文档类型,并使用其他注解指定属性的映射关系,如下所示: ``` @Document(indexName = "my_index", type = "my_type") public class MyDocument { @Id private String id; private String title; private String content; // ... 省略getter和setter方法 } ``` 4. 创建Elasticsearch操作接口 创建一个接口,继承ElasticsearchRepository接口,并指定泛型为步骤3中创建的实体类,如下所示: ``` public interface MyDocumentRepository extends ElasticsearchRepository<MyDocument, String> { } ``` 5. 使用Elasticsearch操作数据 在需要使用Elasticsearch的地方注入MyDocumentRepository,即可使用其提供的方法进行数据的CRUD操作,如下所示: ``` @Autowired private MyDocumentRepository repository; public void save(MyDocument document) { repository.save(document); } public MyDocument findById(String id) { return repository.findById(id).orElse(null); } public void deleteById(String id) { repository.deleteById(id); } ``` 以上就是SpringBoot整合Elasticsearch的基本步骤,希望对你有帮助。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值