idea中es文档增删改查的实现(测试版)

private RestHighLevelClient client;
@BeforeEach   //运行每个@Test之前运行
public void restHighLevelClient(){
    client=new RestHighLevelClient
(RestClient.builder(HttpHost.create("服务器地址")));
}
@Test //修改或新增文档 id不同修新增,相同则删除重写添加
public void addDocument() throws IOException {
    //从数据库查询数据
    IndexRequest request=new IndexRequest(索引库).id(新增至es服务器的文档id);
    request.source(JSON.toJSONString(文档对象转json),XContentType.JSON);
    client.index(request,RequestOptions.DEFAULT);
}

@Test//查询
public void getDocument()throws IOException{
     //设置查询索引
    GetRequest request = new GetRequest(索引库).id(文档id);
     //得到查询结果,转为json对象格式
    GetResponse response = client.get(request, RequestOptions.DEFAULT);
    String sourceAsString = response.getSourceAsString();
    JSON.parseObject(sourceAsString,xx.class);
  
}
@Test//删除文档
public void deleteDocument()throws IOException{
    DeleteRequest request = new DeleteRequest(索引库).id(文档id);
    DeleteResponse response = client.delete(request, RequestOptions.DEFAULT);
     //显示结果
    System.out.println(response.status());
}
@Test//局部修改
public void putDocument()throws IOException {
    UpdateRequest request = new UpdateRequest(索引库,文档id);
    //修改字段
    request.doc(字段,值);
    client.update(request, RequestOptions.DEFAULT);    
}
@Test//批量操作
public void bulkDocument()throws IOException{
    BulkRequest bulkRequest = new BulkRequest(); 
    //可通过add往里面添加
    bulkRequest.add(newIndexRequest(....));
  
    client.bulk(bulkRequest,RequestOptions.DEFAULT);

}
@Test//桶聚合
void aggsBucket() throws IOException{
    SearchRequest searchRequest = new SearchRequest(索引库);
    searchRequest.source().query(QueryBuilders.termQuery(字段,值));
    searchRequest.source().size(0);//不显示查询到的文档具体数据
    //按type分类只显示前5个,xxx用于后续查询结果,为任意名称  
    searchRequest.source().aggregation(AggregationBuilders.terms("xxx").field("type").size(5).subAggregation  //设置子聚合,以color作为分类    (AggregationBuilders.max("ppp").field("color")).order(BucketOrder.key(true)));
     //查询并打印到控制台
    SearchResponse search = client.search(searchRequest, RequestOptions.DEFAULT);
    Terms aggregations = search.getAggregations().get("xxx");
    List buckets = aggregations.getBuckets();
    buckets.forEach(new Consumer() {
        @Override
        public void accept(Terms.Bucket bucket) {
            System.out.println(bucket.getKey());
            System.out.println(JSON.toJSONString(bucket.getAggregations().get("ppp")));
        }
    });
@AfterEach
public void close() throws IOException {
    client.close();
}

你可能感兴趣的:(intellij-idea,elasticsearch,java)