一、ES介绍
1、安装
elastic 的官网 elastic.co/downloads/elasticsearch 获取最新版本的Elasticsearch。解压文档后,按照下面的操作
cd elasticsearch-<version>
./bin/elasticsearch.bat
此时,Elasticsearch运行在本地的9200端口,在浏览器中输入网址“http://localhost:9200/”,
2、概念
3、访问命令
使用postman , PUT类型, http://127.0.0.1:9200/google/emp/1
将HTTP命令由PUT 改为GET可以用来检索文档,同样的,可以使用DELETE命令来删除文档,以及使用HEAD 指令来检查文档是否存在。如果想更新已存在的文档,只需再次PUT。
4、轻量搜索
- GET 是相当简单的,可以直接得到指定的文档。 现在尝试点儿稍微高级的功能,比如一个简单的搜索。我们使用下列请求来搜索所有雇员:
GET /megacorp/employee/_search - 尝试下搜索姓氏为
Smith
的雇员。这个方法一般涉及到一个查询字符串(_query-string)搜索,因为我们通过一个URL参数来传递查
询信息给搜索接口:
GET /megacorp/employee/_search?q=last_name:Smth
二、SpringBoot整合
SpringBoot默认支持两种技术来和ES交互:
- Jest(默认不生效)
- SpringData ElasticSearch
1、Jest
需要导入jest的工具包(io.searchbox.client.JestClient)
(1)核心依赖
<dependency>
<groupId>io.searchbox</groupId>
<artifactId>jest</artifactId>
<version>6.3.1</version>
</dependency>
(2)配置文件
spring.elasticsearch.jestt.uris=192.168.99.100:9200
(3)实体类配置
@Data
public class Article {
@JestId
private Integer id;
private String author;
private String title;
private String content;
(4)调用
@Autowired
JestClient jestClient;
//添加
@Test
void contextLoads() {
Article article = new Article(1, "allen", "王武", "helloworld");
System.err.println(article);
//修改也可以用save
Index index = new Index.Builder(article)
.index("megacorp").type("news").build();
jestClient.execute(index);
}
//获取
@Test
public void search(){
//获取aaa索引中id为1的Article对象
String json = "";
Search search = new Search.Builder(json)
.addIndex("megacorp").addType("news").build();
SearchResult result = jestClient.execute(search );
}
2、SpringData ElasticSearch
注意:SpringData和ES版本需要适配
https://docs.spring.io/spring-data/elasticsearch/docs/current/reference/html/#preface.versions
(1)核心依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-elasticsearch</artifactId>
</dependency>
(2)配置文件
spring.elasticsearch.rest.uris=192.168.99.100:9200
spring.data.elasticsearch.cluster-name=elasticsearch
spring.data.elasticsearch.cluster-nodes=192.168.99.100:9300
(3)实体类配置
@Data
@Document(indexName="megacorp", type="news")
public class Book{
@JestId
private Integer id;
private String author;
private String title;
(4)第一种调用:继承ElasticseanchRepository
public interface BookRepository
extends ElasticseanchRepository<Book,Integer> {
}
@Autowired
BookRepository bookRepository ;
//添加
@Test
void contextLoads() {
Book book = new Book();
bookRepository.index(book);
}
(5)第二种调用: ElasticsearchRestTemplate
@Autowired
ElasticsearchRestTemplate elasticsearchRestTemplate;
//添加
@Test
void contextLoads() {
Article article = new Article(1, "allen", "bbb", "helloworld");
System.err.println(article);
//修改也可以用save
elasticsearchRestTemplate.save(article);
}
//获取
@Test
public void test02(){
//获取aaa索引中id为1的Article对象
Article article = elasticsearchRestTemplate.get("1", Article.class);
System.out.println(article);
}