SpringBoot与检索 ElasticSearch

SpringBoot与检索 ElasticSearch

一、检索

我们的应用经常需要添加检索功能,开源的ElasticSearch是目前全文搜索引|擎的
首选。他可以快速的存储、搜索和分析海量数据。Spring Boot通过整合Spring
Data ElasticSearch为我们提供了非常便捷的检索功能支持;
Elasticsearch是一个分布式搜索服务,提供Restful API,底层基于Lucene,采用
多shard (分片)的方式保证数据安全,并且提供自动resharding的功能,github
等大型的站点也是采用了ElasticSearch作为其搜索服务,

二、概念

  • 以员工文档的形式存储为例:一个文档代表一个员工 数据。存储数据到Elasticsearch的行为叫做索引,但在索引-个文档之前,需要确定将文档存储在哪里。
  • 一个Elasticsearch集群可以包含多个索引,相应的每个索引可以包含多个,类型。这些不同的类型存储着多个文档,每个文档又有 多个属性。
  • 类似关系:
    1.索引-数据库
    2.类型-表
    3.文档-表中的记录
    4.属性-列

三、整合ElasticSearch测试

先看一下对应的目录结构:
3

1. 引入spring-boot-starter-data-elasticsearch

<!--SpringBoot默认使用SpringData ElasticSearch模块进行操作-->
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-data-elasticsearch</artifactId>
		</dependency>
		<!-- https://mvnrepository.com/artifact/io.searchbox/jest -->
		<dependency>
			<groupId>io.searchbox</groupId>
			<artifactId>jest</artifactId>
			<version>5.3.3</version>
		</dependency>

2. 安装Spring Data对应版本的ElasticSearch
这里是在Docker中进行启动并且进行操作
1
测试一下:出现下面这个界面就是正确运行
6

3. application.propertiies配置
2

4.编写一个 ElasticsearchRepository 的子接口来操作ES;

public interface BookRepository extends ElasticsearchRepository<Book,Integer> {

    //参照
    // https://docs.spring.io/spring-data/elasticsearch/docs/3.0.6.RELEASE/reference/html/
   public List<Book> findByBookNameLike(String bookName);

}

5. 测试ElasticSearch

@RunWith(SpringRunner.class)
@SpringBootTest
public class Springboot03ElasticApplicationTests {

	@Autowired
	JestClient jestClient;

	@Autowired
	BookRepository bookRepository;

	@Test
	public void test02(){
//		Book book = new Book();
//		book.setId(1);
//		book.setBookName("西游记");
//		book.setAuthor("吴承恩");
//		bookRepository.index(book);


		for (Book book : bookRepository.findByBookNameLike("游")) {
			System.out.println(book);
		}
	}

	@Test
	public void contextLoads() {
		//1、给Es中索引(保存)一个文档;
		Article article = new Article();
		article.setId(1);
		article.setTitle("好消息");
		article.setAuthor("zhangsan");
		article.setContent("Hello World");

		//构建一个索引功能
		Index index = new Index.Builder(article).index("atguigu").type("news").build();

		try {
			//执行
			jestClient.execute(index);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	//测试搜索
	@Test
	public void search(){

		//查询表达式
		String json ="{\n" +
				"    \"query\" : {\n" +
				"        \"match\" : {\n" +
				"            \"content\" : \"hello\"\n" +
				"        }\n" +
				"    }\n" +
				"}";

		//更多操作:https://github.com/searchbox-io/Jest/tree/master/jest
		//构建搜索功能
		Search search = new Search.Builder(json).addIndex("atguigu").addType("news").build();

		//执行
		try {
			SearchResult result = jestClient.execute(search);
			System.out.println(result.getJsonString());
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

}

测试结果如下图:
7
谢谢!,另外希望大家可以多多访问我的个人博客

天涯志

posted @ 2020-04-16 17:26  xieyj  阅读(871)  评论(1编辑  收藏  举报