先看实体类:
package com.elasticexample.demo.pojo;
import io.searchbox.annotations.JestId;
import lombok.Data;
import lombok.experimental.Accessors;
/**
* @Author lyr
* @create 2020/2/15 22:43
*/
@Data
@Accessors(chain = true)
public class Article {
/**
* 注意 : 如果不手动指定 Jestid, elasticsearch 会把其放入 _source里面,而不是看成一个id,而且会有一个随机的字符串作为 _id
* 如果 指定了 Jestid, 那么这个就是 _id 字段
*/
@JestId
private Integer id;
private String title;
private String content;
private String author;
}
把 数据存入 ES中:
@Test
public void beanIndexCreate()
{
Article article = new Article()
.setId(1)
.setAuthor("lyr")
.setTitle("古诗")
.setContent("休息时间");
Index index = new Index.Builder(article)
.index("datasource01")
.type("tbl_article01")
.build();
try {
//保存为文档
jestClient.execute(index);
} catch (IOException e) {
e.printStackTrace();
}
}
这里有个注意点:如果没有 @Jestid, 我就要在 创建 Index对象的 时候手动指定 jestid
这样:
Index index = new Index.Builder(article)
.index("datasource01")
.type("tbl_article01")
.id("1")
.build();
这个是没有注解时创建的:
下面是有 @JestId时创建的
指定 jestId ,才可以通过 url去访问对应id 的资源
搜索的例子就不写了
用 SearchBuilder 构建搜索条件,传入对应的json查询表达式