Elasticsearch 基本 *** 作 ---- Java API 方式

Elasticsearch 基本 *** 作 ---- Java API 方式,第1张

Elasticsearch 基本 *** 作 ---- Java API 方式 Elasticsearch基本 *** 作

文章目录
  • Elasticsearch基本 *** 作
    • 一、访问ES服务器
    • 二、索引 *** 作
      • 2.1 创建索引
      • 2.2 查看索引
      • 2.3 删除索引
    • 三、文档 *** 作
      • 3.1 创建文档
      • 3.2 修改文档
      • 3.3 查询文档
      • 3.4 删除文档
    • 四、批量 *** 作
      • 4.1 批量插入文档
      • 4.2 批量删除文档
      • 4.3 查询 *** 作

一、访问ES服务器

1. 导入依赖


    org.elasticsearch.client
    elasticsearch-rest-high-level-client
    7.8.0



    com.fasterxml.jackson.core
    jackson-databind
    2.9.9

2. 访问ES服务器

//开启ES客户端
RestHighLevelClient client = new RestHighLevelClient(
    RestClient.builder(new HttpHost("localhost", 9200, "http"))
);

//关闭ES客户端
client.close();
二、索引 *** 作 2.1 创建索引
//开启ES客户端
RestHighLevelClient client = new RestHighLevelClient(
    RestClient.builder(new HttpHost("localhost", 9200, "http"))
);

//创建索引请求,参数中指定索引的名称
CreateIndexRequest indexRequest = new CreateIndexRequest("person");
//发起请求得到响应
CreateIndexResponse response = client.indices().create(indexRequest, RequestOptions.DEFAULT);

//获取响应状态
boolean acknowledged = response.isAcknowledged();
System.out.println("创建索引结果:" + acknowledged); //true

//关闭ES客户端
client.close();
2.2 查看索引
//开启ES客户端
RestHighLevelClient client = new RestHighLevelClient(RestClient.builder(new HttpHost("localhost", 9200, "http")));

//查询索引请求
GetIndexRequest indexRequest = new GetIndexRequest("person");
GetIndexResponse response = client.indices().get(indexRequest, RequestOptions.DEFAULT);

//获取响应状态
System.out.println(Arrays.toString(response.getIndices())); //[person]

//关闭ES客户端
client.close();
2.3 删除索引
//开启ES客户端
RestHighLevelClient esClient = new RestHighLevelClient(
    RestClient.builder(new HttpHost("localhost", 9200, "http"))
);

//发起删除索引请求
DeleteIndexRequest request = new DeleteIndexRequest("person");
AcknowledgedResponse response = esClient.indices().delete(request, RequestOptions.DEFAULT);

//得到响应状态
System.out.println(response.isAcknowledged()); //true

//关闭客户端
esClient.close();
三、文档 *** 作 3.1 创建文档

1. 创建所要插入的文档对象

public class Person {
    private String name;
    private String sex;
    private Integer age;
    //以及Java Bean的其他结构
}

2. 插入文档到对应的索引

import com.fasterxml.jackson.databind.ObjectMapper;

//开启ES服务器
RestHighLevelClient esClient = new RestHighLevelClient(
    RestClient.builder(new HttpHost("localhost", 9200, "http"))
);

//插入数据
IndexRequest request = new IndexRequest();
//参数1表示所要插入的索引,参数2指定插入文档的id值
request.index("person").id("1001");

//给文档对象属性赋值
Person person = new Person();
person.setName("zhangsan");
person.setAge(30);
person.setSex("男");

//向ES插入数据,必须将其转换成JSON格式
ObjectMapper mapper = new ObjectMapper();
String value = mapper.writevalueAsString(person);
//可以理解为携带的JSON格式的请求体
request.source(value, XContentType.JSON);

//得到响应结果
IndexResponse indexResponse = esClient.index(request, RequestOptions.DEFAULT);
System.out.println(indexResponse.getResult()); //CREATED

//关闭ES客户端
esClient.close();
3.2 修改文档
//开启ES服务器
RestHighLevelClient esClient = new RestHighLevelClient(
    RestClient.builder(new HttpHost("localhost", 9200, "http"))
);

//创建修改请求
UpdateRequest request = new UpdateRequest();
//参数1表示所要修改的索引,参数2指定修改文档的id值
request.index("person").id("1001");
//设置请求体,对数据进行修改,参数2表示字段名,参数3表示所要修改的值
request.doc(XContentType.JSON, "sex", "女");

//得到响应结果
UpdateResponse response = esClient.update(request, RequestOptions.DEFAULT);

//关闭ES客户端
esClient.close();
3.3 查询文档
//创建查询请求
GetRequest getRequest = new GetRequest().index("person").id("1001");
GetResponse response = esClient.get(getRequest, RequestOptions.DEFAULT);

//打印结果信息
System.out.println(response.getIndex()); //person
System.out.println(response.getId()); //1001
System.out.println(response.getSourceAsString()); //{"name":"zhangsan","sex":"男","age":"22"}
3.4 删除文档
//开启ES服务器
RestHighLevelClient esClient = new RestHighLevelClient(
    RestClient.builder(new HttpHost("localhost", 9200, "http"))
);

//创建查询请求
DeleteRequest deleteRequest = new DeleteRequest().index("person").id("1001");
DeleteResponse response = esClient.delete(deleteRequest, RequestOptions.DEFAULT);

//打印结果信息
System.out.println(response.getIndex()); //person
System.out.println(response.getId()); //1001

//关闭ES客户端
esClient.close();
四、批量 *** 作 4.1 批量插入文档
// 创建批量 *** 作的请求对象
BulkRequest request = new BulkRequest();

// 一次创建多个文档
request.add(new IndexRequest().index("person").id("1002").source(XContentType.JSON, "name", "lisi", "age", 30, "sex", "女"));
request.add(new IndexRequest().index("person").id("1003").source(XContentType.JSON, "name", "wangwu", "age", 40, "sex", "男"));
request.add(new IndexRequest().index("person").id("1004").source(XContentType.JSON, "name", "wangwu1", "age", 40, "sex", "女"));
request.add(new IndexRequest().index("person").id("1005").source(XContentType.JSON, "name", "wangwu2", "age", 50, "sex", "男"));
request.add(new IndexRequest().index("person").id("1006").source(XContentType.JSON, "name", "wangwu3", "age", 50, "sex", "男"));
request.add(new IndexRequest().index("person").id("1007").source(XContentType.JSON, "name", "wangwu44", "age", 60, "sex", "男"));
request.add(new IndexRequest().index("person").id("1008").source(XContentType.JSON, "name", "wangwu555", "age", 60, "sex", "男"));
request.add(new IndexRequest().index("person").id("1009").source(XContentType.JSON, "name", "wangwu66666", "age", 60, "sex", "男"));

// bulk表示批量 *** 作
BulkResponse response = esClient.bulk(request, RequestOptions.DEFAULT);

// 得到 *** 作的时长
System.out.println(response.getTook()); //14ms
4.2 批量删除文档
// 创建批量 *** 作对象
BulkRequest request = new BulkRequest();

// 添加批量 *** 作
request.add(new DeleteRequest().index("user").id("1002"));
request.add(new DeleteRequest().index("user").id("1003"));

// 执行批量 *** 作
BulkResponse response = esClient.bulk(request, RequestOptions.DEFAULT);

System.out.println(response.getTook()); //12ms
4.3 查询 *** 作

4.3.1 查询索引中的全部文档

// 创建查询请求
SearchRequest request = new SearchRequest();
// 指定查询索引
request.indices("person");

// 指定查询条件,matchAllQuery表示查询所有文档
request.source(new SearchSourceBuilder().query(QueryBuilders.matchAllQuery()));

//执行查询
SearchResponse response = esClient.search(request, RequestOptions.DEFAULT);

// 得到查询结果
SearchHits hits = response.getHits();
System.out.println(hits.getTotalHits());

// 得到查询结果
for ( SearchHit hit : hits ) {
    System.out.println(hit.getSourceAsString());
}

运行结果:

4.3.2 条件查询

SearchRequest request = new SearchRequest();
request.indices("person");

//只查询出age等于30的文档
request.source(new SearchSourceBuilder().query(QueryBuilders.termQuery("age", 30)));
SearchResponse response = esClient.search(request, RequestOptions.DEFAULT);

SearchHits hits = response.getHits();

System.out.println(hits.getTotalHits());
for ( SearchHit hit : hits ) {
    System.out.println(hit.getSourceAsString());
}

4.3.3 分页查询

SearchRequest request = new SearchRequest();
request.indices("person");

// 查询所有文档
SearchSourceBuilder builder = new SearchSourceBuilder().query(QueryBuilders.matchAllQuery());

//设定页码条件
builder.from(2);
builder.size(2);

request.source(builder);

// 得到响应结果
SearchResponse response = esClient.search(request, RequestOptions.DEFAULT);

SearchHits hits = response.getHits();
System.out.println(hits.getTotalHits());
for ( SearchHit hit : hits ) {
    System.out.println(hit.getSourceAsString());
}

4.3.4 查询排序

SearchRequest request = new SearchRequest();
request.indices("person");

SearchSourceBuilder builder = new SearchSourceBuilder().query(QueryBuilders.matchAllQuery());

// 查询结果按照age字段排序
builder.sort("age", SortOrder.DESC);
request.source(builder);

SearchResponse response = esClient.search(request, RequestOptions.DEFAULT);

SearchHits hits = response.getHits();

System.out.println(hits.getTotalHits());
for ( SearchHit hit : hits ) {
    System.out.println(hit.getSourceAsString());
}

4.3.5 过滤字段

SearchRequest request = new SearchRequest();
request.indices("person");

SearchSourceBuilder builder = new SearchSourceBuilder().query(QueryBuilders.matchAllQuery());

// 结果不包含age字段
String[] excludes = {"age"};
String[] includes = {};
builder.fetchSource(includes, excludes);

request.source(builder);
SearchResponse response = esClient.search(request, RequestOptions.DEFAULT);

SearchHits hits = response.getHits();
System.out.println(hits.getTotalHits());
for ( SearchHit hit : hits ) {
    System.out.println(hit.getSourceAsString());
}

4.3.6 多个条件组合查询

SearchRequest request = new SearchRequest();
request.indices("person");

SearchSourceBuilder builder = new SearchSourceBuilder();

// boolQuery表示组合查询
BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();

//must表示且
//boolQueryBuilder.must(QueryBuilders.matchQuery("age", 30));
//boolQueryBuilder.must(QueryBuilders.matchQuery("sex", "男"));

//should表示或,也就是说age等于30或40的人都可以查询出来
boolQueryBuilder.should(QueryBuilders.matchQuery("age", 30));
boolQueryBuilder.should(QueryBuilders.matchQuery("age", 40));

builder.query(boolQueryBuilder);

request.source(builder);
SearchResponse response = esClient.search(request, RequestOptions.DEFAULT);

SearchHits hits = response.getHits();

System.out.println(hits.getTotalHits());

for ( SearchHit hit : hits ) {
    System.out.println(hit.getSourceAsString());
}

4.3.7 范围查询

SearchRequest request = new SearchRequest();
request.indices("person");

SearchSourceBuilder builder = new SearchSourceBuilder();

// 对age字段进行范围查询
RangeQueryBuilder rangeQuery = QueryBuilders.rangeQuery("age");

// age大于等于30,小于50
rangeQuery.gte(30);
rangeQuery.lt(50);

builder.query(rangeQuery);

request.source(builder);
SearchResponse response = esClient.search(request, RequestOptions.DEFAULT);

SearchHits hits = response.getHits();
System.out.println(hits.getTotalHits());
for ( SearchHit hit : hits ) {
    System.out.println(hit.getSourceAsString());
}

4.3.8 模糊查询

SearchRequest request = new SearchRequest();
request.indices("person");

SearchSourceBuilder builder = new SearchSourceBuilder();

//fuzzyQuery表示模糊查询
//Fuzziness.TWO表示范围查询的步长,此处表示可以查询到与wangwu两个位置不同的结果
builder.query(QueryBuilders.fuzzyQuery("name", "wangwu").fuzziness(Fuzziness.TWO));

request.source(builder);
SearchResponse response = esClient.search(request, RequestOptions.DEFAULT);

4.3.9 聚合查询

  • 求最大值
SearchRequest request = new SearchRequest();
request.indices("person");

SearchSourceBuilder builder = new SearchSourceBuilder();

//求age字段的最大值,结果名称是maxAge
AggregationBuilder aggregationBuilder = AggregationBuilders.max("maxAge").field("age");
builder.aggregation(aggregationBuilder);

request.source(builder);
SearchResponse response = esClient.search(request, RequestOptions.DEFAULT);
  • 分组查询
SearchRequest request = new SearchRequest();
request.indices("person");

SearchSourceBuilder builder = new SearchSourceBuilder();

//对age字段进行分组
AggregationBuilder aggregationBuilder = AggregationBuilders.terms("ageGroup").field("age");
builder.aggregation(aggregationBuilder);

request.source(builder);
SearchResponse response = esClient.search(request, RequestOptions.DEFAULT);

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/5679174.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-17
下一篇 2022-12-17

发表评论

登录后才能评论

评论列表(0条)

保存