Java 操作ElasticSearch

这篇博客详细介绍了如何使用Java的RestHighLevelClient连接并操作ElasticSearch,包括创建、检查、删除索引,以及增加、查询、更新和删除文档。还展示了批量处理请求和条件查询的实现,为ElasticSearch的日常开发提供了清晰的步骤和示例。
摘要由CSDN通过智能技术生成

Java 操作ElasticSearch

1、连接ElasticSearch服务器

@Configuration
public class ElasticSearchClientConfig {

    private static final String CLUSTER_NAME = "*******************************";
    private static final String APP_KEY = "******************************";
    private static final String ACCESS_KEY = "********************************";

    @Bean
    public RestHighLevelClient restHighLevelClient() {
        return PorosHighLevelClientBuilder.builder()
                .clusterName(CLUSTER_NAME) // required
                .appKey(APP_KEY) // required
                .accessKey(ACCESS_KEY) // required
                //.timeoutMillis(10_000) // optional, 默认 30_000
                .build();
    }
}

2、准备工作

@Data
@NoArgsConstructor
@AllArgsConstructor
public class User {

    private String username;
    private Integer age;
}

3、增删改查(index)

3.1 注入RestHighLevelClient

@Autowired
RestHighLevelClient restHighLevelClient;

3.2 创建index

@Test
public void testCreateIndex() throws IOException {
  // 1、创建索引请求
  CreateIndexRequest request = new CreateIndexRequest("lcc_index");
  // 2、客户端发送请求
  CreateIndexResponse createIndexResponse = restHighLevelClient.indices().create(request, RequestOptions.DEFAULT);

  log.info(createIndexResponse.toString());
}

3.3 判断是否存在index

@Test
public void testGetIndex() throws IOException {
  GetIndexRequest request = new GetIndexRequest("lcc_index");
  boolean exists = restHighLevelClient.indices().exists(request, RequestOptions.DEFAULT);
  log.info(exists + "");
}

3.4 删除index

@Test
public void testDeleteIndex() throws IOException {
  DeleteIndexRequest request = new DeleteIndexRequest("lcc_index");
  AcknowledgedResponse delete = restHighLevelClient.indices().delete(request, RequestOptions.DEFAULT);
  log.info(delete.toString());
}

4、增删改查document

4.1创建document

@Test
public void testAddDocument() throws IOException {
  // 创建对象
  User user = new User("lcc", 3);
  // 创建请求
  IndexRequest request = new IndexRequest("lcc_index");

  // put /lcc_index/_doc/1
  request.id("1");
  request.timeout(TimeValue.timeValueSeconds(1));

  // 数据放入请求
  Gson gson = new Gson();
  request.source(gson.toJson(user), XContentType.JSON);

  // 发送请求
  IndexResponse indexResponse = restHighLevelClient.index(request, RequestOptions.DEFAULT);

  log.info(indexResponse.toString());
}

4.2判断document是否存在

@Test
public void testExistDocument() throws IOException {
  GetRequest request = new GetRequest("lcc_index", "1");
  // 不获取 _source 上下文
  request.fetchSourceContext(new FetchSourceContext(false));
  // 按哪个字段排序
  request.storedFields("_none_");
  // 客户端发送请求
  boolean exists = restHighLevelClient.exists(request, RequestOptions.DEFAULT);
  log.info(exists + "");
}

4.3获得document

@Test
public void testGetDocument() throws IOException {
  GetRequest request = new GetRequest("lcc_index", "1");
  GetResponse documentFields = restHighLevelClient.get(request, RequestOptions.DEFAULT);
  log.info(documentFields.getSource().toString());
}

4.4更新document

@Test
public void testUpdateDocument() throws IOException {
  UpdateRequest request = new UpdateRequest("lcc_index", "1");
  User user = new User();
  user.setAge(5);
  Gson gson = new Gson();
  request.doc(gson.toJson(user), XContentType.JSON);
  UpdateResponse update = restHighLevelClient.update(request, RequestOptions.DEFAULT);
  log.info(update.toString());
}

4.5删除document

@Test
public void testDeleteDocument() throws IOException {
  DeleteRequest request = new DeleteRequest("lcc_index", "1");

  DeleteResponse delete = restHighLevelClient.delete(request, RequestOptions.DEFAULT);
  log.info(delete.status() + "");
}

5、批量操作(批量发送请求)

@Test
public  void testBulkRequest() throws IOException {
  BulkRequest request = new BulkRequest("lcc_index");
  request.timeout("10s");

  List<User> list = Lists.newArrayList();
  for (int i = 0; i < 10; i++) {
    list.add(new User("lcc" + i, i));
  }
  Gson gson = new Gson();
  for (int i = 0; i < 10; i++) {
    request.add(new IndexRequest()
                .id((i+1) + "")
                .source(gson.toJson(list.get(i)), XContentType.JSON));
  }

  BulkResponse bulk = restHighLevelClient.bulk(request, RequestOptions.DEFAULT);
  log.info(bulk.hasFailures() + "");
}

6、条件查询(高级)

@Test
public void testSearch() throws IOException {
  SearchRequest searchRequest = new SearchRequest("lcc_index");

  // 构造查询条件
  SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
  TermQueryBuilder termQueryBuilder = QueryBuilders.termQuery("name", "lcc1");// 精准匹配
  searchSourceBuilder.query(termQueryBuilder);

  // 查询条件放入请求
  searchRequest.source(searchSourceBuilder);

  // 客户端请求查询
  SearchResponse search = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);
  log.info(search.getHits() + "");
  for (SearchHit hit : search.getHits().getHits()) {
    log.info(hit.getSourceAsMap() + "");

  }
}
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值