一、Elasticsearch简介
Elasticsearch是一个分布式搜索服务,提供Restful API,底层基于Lucene,采用多shard(分片)的方式保证数据安全,并且提供自动resharding的功能,github等大型站点也是采用了Elasticsearch作为其搜索服务。
二、安装Elasticsearch
1.docker查看有没有相关的镜像,命令:docker search elasticsearch
2.下载命令:docker pull elasticsearch
3.运行:docker run -e ES_JAVA_OPTS="-Xms256m -Xmx256m" -d -p 9200:9200 -p9300:9300 --name ES01 IMAGE_ID(镜像ID)
4.访问ip:9200即可访问。
三、Elasticsearch流程图
四、springboot整合elasticsearch
1.引入spring-boot-starter-data-elasticsearch
2.安装Spring Data对应版本的Elasticsearch
3.application.yml配置
4.Spring Boot自动配置的ElasticsearchRepository、ElasticsearchTemplate、Client
5.测试Elasticsearch
五、使用代码
SpringBoot默认支持两种技术来和ES交互 1、Jest(默认不生效) 需要导入jest的工具包(io.searchbox.client.JestClient)
<dependency>
<groupId>io.searchbox</groupId>
<artifactId>jest</artifactId>
<version>5.3.3</version>
</dependency>
#application.properties配置
spring.elasticsearch.jest.uris=http://106.15.72.13:9200
package com.atguidu.elasticsearch;
import com.atguidu.elasticsearch.bean.BookContent;
import io.searchbox.client.JestClient;
import io.searchbox.core.Index;
import io.searchbox.core.Search;
import io.searchbox.core.SearchResult;
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.io.IOException;
@RunWith(SpringRunner.class)
@SpringBootTest
public class ElasticsearchApplicationTests {
@Autowired
JestClient jestClient;
@Test
public void contextLoads() {
//1、给Es中索引(保存)一个文档:
BookContent bookContent = new BookContent();
bookContent.setDi(1);
bookContent.setTitle("好消息");
bookContent.setAuthor("zhansan");
bookContent.setContent("Hello world");
//构建一个索引功能
Index index = new Index.Builder(bookContent).index("atguidu").type("news").build();
try {
jestClient.execute(index);
} catch (IOException e) {
e.printStackTrace();
}
}
@Test
public void search() {
String json = "";
//构建搜索
Search search = new Search.Builder(json).addIndex("atguidu").addType("news").build();
//执行
try {
SearchResult searchResult = jestClient.execute(search);
System.out.println(searchResult.getJsonString());
} catch (IOException e) {
e.printStackTrace();
}
}
}
2、SpringData ElasticSearch
版本适配说明:Es与springboot版本不一致会导致无法连接,需要升级一方的版本
1)、client节点信息clusterNodes: clusterName
2)、ElasticsearchTemplate 操作Es
- 新增实体类book加上注解:
@Document(indexName = "atguidu",type = "book")
- 新增repository
public interface BookRepository extends ElasticsearchRepository { }
- 新增实体类
@Autowired BookRepository bookRepository; public void test02(){ Book book = new Book(); book.setDi(1); book.setAuthor("吴承恩"); book.setContent("三大白骨精"); book.setTitle("西游记"); bookRepository.index(book); }