ElasticSearch Java API只需十招,轻松掌握变专家!
创始人
2025-07-03 10:10:20
0

环境:springboot2.4.12 + elasticsearch7.8.0

      Elasticsearch是一种开源的、分布式的、实时的搜索和分析引擎。它允许你存储,搜索和分析大量数据,通常用于为网站或应用程序提供强大的搜索功能。

      Java API是Elasticsearch提供的官方客户端,它允许Java开发者轻松地与Elasticsearch服务器进行交互。下面是一些关于如何使用Java API来调用Elasticsearch的常用方法。

注意:这里为了方便使用springboot项目(避免还要单独引用其它包)

相关依赖


  org.springframework.boot
  spring-boot-starter-web


  org.elasticsearch
  elasticsearch
  7.8.0


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

索引操作

高级别的Rest客户端对象

private static RestHighLevelClient client = 
  new RestHighLevelClient(RestClient.builder(
    new HttpHost("localhost", 9200, "http"))) ;

1. 创建索引

public static void createIndex(String index) throws Exception {
  CreateIndexRequest request = new CreateIndexRequest(index) ;
  CreateIndexResponse response = client.indices().create(request, RequestOptions.DEFAULT) ;
  boolean ack = response.isAcknowledged() ;
  System.out.println("ack = " + ack) ;
}

2. 查看索引

public static void viewIndex(String index) throws Exception {
  GetIndexRequest request = new GetIndexRequest(index) ;
  GetIndexResponse response = client.indices().get(request, RequestOptions.DEFAULT) ;
  System.out.println("aliases: " + response.getAliases() + "\n"
    + "mappings: " + response.getMappings() + "\n"
    + "settings: " + response.getSettings()) ;
}

3. 删除索引

public static void deleteIndex(String index) throws Exception {
  DeleteIndexRequest request = new DeleteIndexRequest(index) ;
  AcknowledgedResponse response = client.indices().delete(request, RequestOptions.DEFAULT) ;
  System.out.println("ack: " + response.isAcknowledged()) ;
}

文档操作

private static RestHighLevelClient client = new RestHighLevelClient(RestClient.builder(new HttpHost("localhost", 9200, "http"))) ;

1. 创建文档

public static void createDoc(String index, Users users) throws Exception {
  IndexRequest request = new IndexRequest() ;
  // 设置索引及唯一标识
  request.index(index).id("1001") ;
  ObjectMapper objectMapper = new ObjectMapper() ;
  String jsonString = objectMapper.writeValueAsString(users) ;
  // 添加文档数据及数据格式
  request.source(jsonString, XContentType.JSON) ;
  IndexResponse response = client.index(request, RequestOptions.DEFAULT) ;
  System.out.println("_index: " + response.getIndex() + "\n"
      + "_id: " + response.getId() + "\n"
      + "_result: " + response.getResult()) ;
}

2. 更新文档

public static void updateDoc(String index, String id) throws Exception {
  UpdateRequest request = new UpdateRequest() ;
  // 配置修改参数
  request.index(index).id(id) ;
  Map source = new HashMap<>() ;
  source.put("sex", "女") ;
  request.doc(source, XContentType.JSON) ;
  UpdateResponse response = client.update(request, RequestOptions.DEFAULT) ;
  System.out.println("_index: " + response.getIndex() + "\n"
      + "_id: " + response.getId() + "\n"
      + "_result: " + response.getResult()) ;
}

3. 查询文档

public static void viewDoc(String index, String id) throws Exception {
  GetRequest request = new GetRequest().index(index).id(id) ;
  GetResponse response = client.get(request, RequestOptions.DEFAULT) ;
  System.out.println("_index: " + response.getIndex() + "\n"
      + "_type: " + response.getType() + "\n"
      + "_id: " + response.getId() + "\n"
      + "source: " + response.getSourceAsString()) ;
}

4. 删除文档

public static void deleteIndex(String index, String id) throws Exception {
  DeleteRequest request = new DeleteRequest().index(index).id(id) ;
  DeleteResponse response = client.delete(request, RequestOptions.DEFAULT) ;
  System.out.println(response.toString()) ;
}

5. 批量操作

public static void batchOperator(String index) throws Exception {
  BulkRequest request = new BulkRequest() ;
  request.add(new IndexRequest().index(index).id("1002").source(XContentType.JSON, "name","老六", "sex", "男", "age", 20)) ;
  request.add(new IndexRequest().index(index).id("1003").source(XContentType.JSON, "name","外网", "sex", "女", "age", 10)) ;
  request.add(new IndexRequest().index(index).id("1004").source(XContentType.JSON, "name","莉莉", "sex", "女", "age", 35)) ;
  BulkResponse response = client.bulk(request, RequestOptions.DEFAULT) ;
  System.out.println("took: " + response.getTook() + "\n"
      + "items: " + new ObjectMapper().writeValueAsString(response.getItems())) ;
}

6. 高级查询

public static void highSearch(String index) throws Exception {
  SearchRequest request = new SearchRequest().indices(index) ;
  SearchSourceBuilder builder = new SearchSourceBuilder() ;
  builder.query(QueryBuilders.matchAllQuery()) ;
  request.source(builder) ;
  SearchResponse response = client.search(request, RequestOptions.DEFAULT) ;
  SearchHits hits = response.getHits() ;
  System.out.println("took: " + response.getTook() + "\n"
      + "timeout: " + response.isTimedOut() + "\n"
      + "total: " + hits.getTotalHits() + "\n"
      + "MaxScore: " + hits.getMaxScore()) ;
  for (SearchHit hit : hits) {
    System.out.println(hit.getSourceAsString()) ;
  }
}

7. term精确查询

public static void highTermSearch(String index) throws Exception {
  SearchRequest request = new SearchRequest().indices(index) ;
  SearchSourceBuilder builder = new SearchSourceBuilder() ;
  builder.query(QueryBuilders.termQuery("age", "20")) ;
  request.source(builder) ;
  SearchResponse response = client.search(request, RequestOptions.DEFAULT) ;
  SearchHits hits = response.getHits() ;
  System.out.println("took: " + response.getTook() + "\n"
      + "timeout: " + response.isTimedOut() + "\n"
      + "total: " + hits.getTotalHits() + "\n"
      + "MaxScore: " + hits.getMaxScore()) ;
  for (SearchHit hit : hits) {
    System.out.println(hit.getSourceAsString()) ;
  }
}

8. 分页查询

public static void highPagingSearch(String index) throws Exception {
  SearchRequest request = new SearchRequest().indices(index) ;
  SearchSourceBuilder builder = new SearchSourceBuilder() ;
  builder.query(QueryBuilders.matchAllQuery()) ;
  builder.from(1) ;
  builder.size(2) ;
  request.source(builder) ;
  SearchResponse response = client.search(request, RequestOptions.DEFAULT) ;
  SearchHits hits = response.getHits() ;
  System.out.println("took: " + response.getTook() + "\n"
      + "timeout: " + response.isTimedOut() + "\n"
      + "total: " + hits.getTotalHits() + "\n"
      + "MaxScore: " + hits.getMaxScore()) ;
  for (SearchHit hit : hits) {
    System.out.println(hit.getSourceAsString()) ;
  }
}

9. 分页&排序查询

public static void highPagingAndSortSearch(String index) throws Exception {
  SearchRequest request = new SearchRequest().indices(index) ;
  SearchSourceBuilder builder = new SearchSourceBuilder() ;
  builder.query(QueryBuilders.matchAllQuery()) ;
  builder.from(0) ;
  builder.size(20) ;
  builder.sort("age", SortOrder.ASC) ;
  request.source(builder) ;
  SearchResponse response = client.search(request, RequestOptions.DEFAULT) ;
  SearchHits hits = response.getHits() ;
  System.out.println("took: " + response.getTook() + "\n"
      + "timeout: " + response.isTimedOut() + "\n"
      + "total: " + hits.getTotalHits() + "\n"
      + "MaxScore: " + hits.getMaxScore()) ;
  for (SearchHit hit : hits) {
    System.out.println(hit.getSourceAsString()) ;
  }
}

10. 分页&排序&过滤字段查询

public static void highPagingAndSortAndFilterFieldSearch(String index) throws Exception {
  SearchRequest request = new SearchRequest().indices(index) ;
  SearchSourceBuilder builder = new SearchSourceBuilder() ;
  builder.query(QueryBuilders.matchAllQuery()) ;
  builder.from(0) ;
  builder.size(20) ;
  builder.sort("age", SortOrder.ASC) ;
  String[] includes = {"name"} ;
  String[] excludes = {} ;
  builder.fetchSource(includes, excludes) ;
  request.source(builder) ;
  SearchResponse response = client.search(request, RequestOptions.DEFAULT) ;
  SearchHits hits = response.getHits() ;
  System.out.println("took: " + response.getTook() + "\n"
      + "timeout: " + response.isTimedOut() + "\n"
      + "total: " + hits.getTotalHits() + "\n"
      + "MaxScore: " + hits.getMaxScore()) ;
  for (SearchHit hit : hits) {
    System.out.println(hit.getSourceAsString()) ;
  }
}

11. 范围查询

public static void highBoolSearch(String index) throws Exception {
  SearchRequest request = new SearchRequest().indices(index) ;
  SearchSourceBuilder builder = new SearchSourceBuilder() ;
  builder.query(QueryBuilders.matchAllQuery()) ;
  builder.from(0) ;
  builder.size(20) ;
  builder.sort("age", SortOrder.ASC) ;
  RangeQueryBuilder rangeBuilder = QueryBuilders.rangeQuery("age");
  rangeBuilder.gte(15) ;
  rangeBuilder.lte(30) ;
  builder.query(rangeBuilder) ;
  request.source(builder) ;
  SearchResponse response = client.search(request, RequestOptions.DEFAULT) ;
  SearchHits hits = response.getHits() ;
  System.out.println("took: " + response.getTook() + "\n"
      + "timeout: " + response.isTimedOut() + "\n"
      + "total: " + hits.getTotalHits() + "\n"
      + "MaxScore: " + hits.getMaxScore()) ;
  for (SearchHit hit : hits) {
    System.out.println(hit.getSourceAsString()) ;
  }
}

12. 高亮查询

public static void highHighLightSearch(String index) throws Exception {
  SearchRequest request = new SearchRequest().indices(index) ;
  SearchSourceBuilder builder = new SearchSourceBuilder() ;
  builder.query(QueryBuilders.matchQuery("name", "莉莉")) ;
  HighlightBuilder highLightBuilder = new HighlightBuilder() ;
  highLightBuilder.preTags("") ;
  highLightBuilder.postTags("") ;
  highLightBuilder.field("name") ;
  builder.highlighter(highLightBuilder) ;
  request.source(builder) ;
  SearchResponse response = client.search(request, RequestOptions.DEFAULT) ;
  SearchHits hits = response.getHits() ;
  System.out.println("took: " + response.getTook() + "\n"
      + "timeout: " + response.isTimedOut() + "\n"
      + "total: " + hits.getTotalHits() + "\n"
      + "MaxScore: " + hits.getMaxScore()) ;
  for (SearchHit hit : hits) {
    System.out.println(hit.getSourceAsString() + "\n"
        + "highlight: " + hit.getHighlightFields()) ;
  }
}

13. 聚合查询

public static void highAggsSearch(String index) throws Exception {
  SearchRequest request = new SearchRequest().indices(index) ;
  SearchSourceBuilder builder = new SearchSourceBuilder() ;
  builder.aggregation(AggregationBuilders.avg("avg_age").field("age")) ;
  request.source(builder) ;
  SearchResponse response = client.search(request, RequestOptions.DEFAULT) ;
  SearchHits hits = response.getHits() ;
  System.out.println("took: " + response.getTook() + "\n"
      + "timeout: " + response.isTimedOut() + "\n"
      + "total: " + hits.getTotalHits() + "\n"
      + "MaxScore: " + hits.getMaxScore()) ;
  for (SearchHit hit : hits) {
    System.out.println(hit.getSourceAsString())  ;
  }
  System.out.println(((ParsedAvg)response.getAggregations().iterator().next()).getValue()) ;
}

14. 分组统计

public static void highGroupSearch(String index) throws Exception {
  SearchRequest request = new SearchRequest().indices(index) ;
  SearchSourceBuilder builder = new SearchSourceBuilder() ;
  builder.aggregation(AggregationBuilders.terms("age_groupby").field("age")) ;
  request.source(builder) ;
  SearchResponse response = client.search(request, RequestOptions.DEFAULT) ;
  SearchHits hits = response.getHits() ;
  System.out.println("took: " + response.getTook() + "\n"
      + "timeout: " + response.isTimedOut() + "\n"
      + "total: " + hits.getTotalHits() + "\n"
      + "MaxScore: " + hits.getMaxScore()) ;
  for (SearchHit hit : hits) {
    System.out.println(hit.getSourceAsString()) ;
  }
  System.out.println(response) ;
}

完毕!!!

相关内容

热门资讯

如何允许远程连接到MySQL数... [[277004]]【51CTO.com快译】默认情况下,MySQL服务器仅侦听来自localhos...
如何利用交换机和端口设置来管理... 在网络管理中,总是有些人让管理员头疼。下面我们就将介绍一下一个网管员利用交换机以及端口设置等来进行D...
施耐德电气数据中心整体解决方案... 近日,全球能效管理专家施耐德电气正式启动大型体验活动“能效中国行——2012卡车巡展”,作为该活动的...
20个非常棒的扁平设计免费资源 Apple设备的平面图标PSD免费平板UI 平板UI套件24平图标Freen平板UI套件PSD径向平...
德国电信门户网站可实时显示全球... 德国电信周三推出一个门户网站,直观地实时提供其安装在全球各地的传感器网络检测到的网络攻击状况。该网站...
为啥国人偏爱 Mybatis,... 关于 SQL 和 ORM 的争论,永远都不会终止,我也一直在思考这个问题。昨天又跟群里的小伙伴进行...
《非诚勿扰》红人闫凤娇被曝厕所... 【51CTO.com 综合消息360安全专家提醒说,“闫凤娇”、“非诚勿扰”已经被黑客盯上成为了“木...
2012年第四季度互联网状况报... [[71653]]  北京时间4月25日消息,据国外媒体报道,全球知名的云平台公司Akamai Te...