<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-data-elasticsearchartifactId>
dependency>
@Configuration
@PropertySource("classpath:application.properties")
public class ElasticSearchConfig {
@Value("${es.host}")
private String host; //绑定配置文件
@Value("${es.port}")
private int port;
@Value("${es.scheme}")
private String scheme;
@Bean
public RestHighLevelClient restHighLevelClient() {
RestHighLevelClient client = new RestHighLevelClient(
RestClient.builder(
new HttpHost(host, port, scheme)));
return client;
}
}
application.propertie
es.host=xx.xx.xx.xx
es.port=9200
es.scheme=http
特点:始终使用面向对象的方式操作ES
相关注解
@Data
@Document(indexName = "products") //指定索引名 索引默认不存在时自动创建
public class Product {
//@Id注解 指定id属性为 文档的_id
@Id
private Integer id;
@Field(type = FieldType.Keyword)
private String title;
@Field(type = FieldType.Double)
private Double price;
@Field(type = FieldType.Text, analyzer = "ik_max_word") //指定使用ik分词器
private String description;
}
插入更新文档
@Test
void test(){
Product product = new Product();
product.setId(1);
product.setPrice(1.23d);
product.setTitle("xxx");
product.setDescription("凯文杜兰特真帅");
//当文档_id不存在时添加,存在时更新,注意:此更新不会保留原始字段,
elasticsearchOperations.save(product);
}
根据id查询文档
Product res = elasticsearchOperations.get("1", Product.class);
删除文档
//返回删除文档的id
String delete = elasticsearchOperations.delete("1", Product.class);
查询所有
SearchHits<Product> searchHits = elasticsearchOperations.search(Query.findAll(), Product.class);
searchHits.forEach(productSearchHit -> {
System.out.println(productSearchHit.getContent()); //获取数据
});
PUT /products/
{
"mappings": {
"properties": {
"id":{
"type":"integer"
},
"title":{
"type":"keyword"
},
"price":{
"type":"double"
},
"created_at":{
"type": "date"
},
"description":{
"type": "text"
}
}
}
}
||
/
@Test
void test() throws IOException {
CreateIndexRequest createIndexRequest = new CreateIndexRequest("products"); //索引名
//映射
createIndexRequest.mapping("{\n" +
" \"properties\": {\n" +
" \"id\":{\n" +
" \"type\":\"integer\"\n" +
" },\n" +
" \"title\":{\n" +
" \"type\":\"keyword\"\n" +
" },\n" +
" \"price\":{\n" +
" \"type\":\"double\"\n" +
" },\n" +
" \"created_at\":{\n" +
" \"type\": \"date\"\n" +
" },\n" +
" \"description\":{\n" +
" \"type\": \"text\"\n" +
" }\n" +
" }\n" +
" }", XContentType.JSON);
CreateIndexResponse createIndexResponse = restHighLevelClient.indices().create(createIndexRequest, RequestOptions.DEFAULT);
System.out.println(createIndexResponse.isAcknowledged()); //是否创建成功
}
@Test
void test() throws IOException {
AcknowledgedResponse response = restHighLevelClient.indices().delete(new DeleteIndexRequest("products"), RequestOptions.DEFAULT);
System.out.println(response.isAcknowledged()); //判断是否成功
}
插入文档也可以像创建索引一样,在kibana中语句写好,然后直接复制到程序中运行,但是我们一般不那样做,我们一般都是将对象进行JSON序列化,然后进行插入。
定义实体类
@JSONField注解,当序列化对象或者反序列化时,使用配置的属性名
public class Product {
private Integer id;
private String title;
private Double price;
@JSONField(name = "create_at", format = "yyyy-MM-dd hh:mm:ss")
private Date createAt;
private String description;
}
插入文档
@Test
void x() throws IOException {
//创建一个IndexRequest(),传入的是索引名
IndexRequest request = new IndexRequest("products");
Product product = new Product();
product.setId(34);
product.setDescription("速度");
product.setPrice(12.32d);
product.setCreateAt(new Date());
//序列化对象为JSON
String data = JSONObject.toJSONString(product);
//指定_id进行插入,数据格式为JSON
request.id("34").source(data, XContentType.JSON);
IndexResponse response = restHighLevelClient.index(request, RequestOptions.DEFAULT);
//获取响应结果
System.out.println(response.getResult());
}
@Test
void del() throws IOException {
//操作products索引
DeleteRequest deleteRequest = new DeleteRequest("products");
deleteRequest.id("1"); //删除_id为1的
DeleteResponse response = restHighLevelClient.delete(deleteRequest, RequestOptions.DEFAULT);
//获取结果
System.out.println(response.getResult());
}
//有哪个字段就更新哪个字段,会保留原始字段
@Test
void update() throws IOException {
UpdateRequest updateRequest = new UpdateRequest("products", "2");
Product product = new Product();
product.setDescription("凯文杜兰特");
updateRequest.doc(JSONObject.toJSONString(product), XContentType.JSON);
UpdateResponse response = restHighLevelClient.update(updateRequest, RequestOptions.DEFAULT);
System.out.println(response.getResult());
}
@Test
void getById() throws IOException {
GetRequest request = new GetRequest("products");
request.id("2");
GetResponse response = restHighLevelClient.get(request, RequestOptions.DEFAULT);
String source = response.getSourceAsString(); //获取JSON数据
//反序列化
Product product = JSONObject.parseObject(source, Product.class);
}
@Test
void batchInsert() throws IOException {
//数据集合
List<Product> products = new ArrayList();
//批量请求
BulkRequest bulkRequest = new BulkRequest();
//遍历集合
for (Product product : products) {
IndexRequest request = new IndexRequest("products"); //添加请求
request.id(product.getId().toString()); //指定id
request.source(JSONObject.toJSONString(product), XContentType.JSON); //加入数据
bulkRequest.add(request); //将配置好的添加请求加入到bulkRequest中
}
//发送请求
BulkResponse responses = restHighLevelClient.bulk(bulkRequest, RequestOptions.DEFAULT);
//获取响应
for (BulkItemResponse respons : responses) {
BulkItemResponse.Failure failure = respons.getFailure();
if (failure == null) {
//成功
System.out.println(respons.getId()); //成功的_id
} else {
//失败
System.out.println(respons.getId()); //失败的id
}
}
}
@Test
void batchDel() throws IOException {
List<Product> list = new ArrayList<>();
BulkRequest bulkRequest = new BulkRequest();
for (Product product : list) {
DeleteRequest deleteRequest = new DeleteRequest("product"); //指定索引
deleteRequest.id(product.getId().toString()); //指定删除的id
bulkRequest.add(deleteRequest); //添加到批量请求中
}
//发送批量删除数据请求
BulkResponse responses = restHighLevelClient.bulk(bulkRequest, RequestOptions.DEFAULT);
//获取响应
for (BulkItemResponse respons : responses) {
BulkItemResponse.Failure failure = respons.getFailure();
if (failure == null) {
//成功
System.out.println(respons.getId()); //成功的_id
} else {
//失败
System.out.println(respons.getId()); //失败的id
}
}
}
@Test
void queryAll() throws IOException {
//创建一个查询请求
SearchRequest searchRequest = new SearchRequest();
//查询的索引名
searchRequest.indices("products");
//构建一个查询条件
SearchSourceBuilder builder = new SearchSourceBuilder();
//构造条件
builder.query(QueryBuilders.matchAllQuery());
searchRequest.source(builder);
//发送请求
SearchResponse response = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);
//获取数据
for (SearchHit hit : response.getHits().getHits()) {
Product product = JSONObject.parseObject(hit.getSourceAsString(), Product.class);
System.out.println(product);
}
}
@Test
void termQ() throws IOException {
//创建一个查询请求
SearchRequest searchRequest = new SearchRequest();
//查询的索引名
searchRequest.indices("products");
//构建一个查询
SearchSourceBuilder builder = new SearchSourceBuilder();
//构造条件 term查询
builder.query(QueryBuilders.termQuery("description", "杜兰特"));
searchRequest.source(builder);
//发送请求
SearchResponse response = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);
//获取数据
for (SearchHit hit : response.getHits().getHits()) {
Product product = JSONObject.parseObject(hit.getSourceAsString(), Product.class);
System.out.println(product);
}
}
@Test
void pageQ() throws IOException {
//创建一个查询请求
SearchRequest searchRequest = new SearchRequest();
//查询的索引名
searchRequest.indices("products");
//构建一个查询
SearchSourceBuilder builder = new SearchSourceBuilder();
//构造条件
builder.query(QueryBuilders.matchAllQuery());
//需要第几页的数据
int pageNo = 1;
//一页的记录数
int pageSize = 2;
int from = (pageNo - 1) * pageSize;
//构建分页
builder.from(from);
builder.size(pageSize);
searchRequest.source(builder);
//发送请求
SearchResponse response = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);
//获取数据
for (SearchHit hit : response.getHits().getHits()) {
Product product = JSONObject.parseObject(hit.getSourceAsString(), Product.class);
System.out.println(product);
}
}
builder.sort("price", SortOrder.DESC);
//如果需要的属性很少,那么就使用includes,excludes设为空
//如果需要的属性很多,那么就使用excludes,includes设为空
String[] includes = {"field1", "field2"};
String[] excludes = {"field3", "field4"};
builder.fetchSource(includes, excludes);
BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
boolQueryBuilder.should(QueryBuilders.matchQuery("price", 23.1));
boolQueryBuilder.should(QueryBuilders.matchQuery("price", 22.3));
builder.query(boolQueryBuilder);
参考1
参考2