RestHighLevelAPI示例

本文介绍了如何通过Java的RestHighLevelClient进行Elasticsearch的操作,包括创建客户端、查询、插入和更新数据。示例代码详细展示了如何实现特定的查询需求和数据更新策略。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

创建客户端

public static RestHighLevelClient getClient() {
	String elasticsearchHosts = "10.1.24.223:9200,10.1.24.224:9200,10.1.24.225:9200";
    String[] hosts = elasticsearchHosts.split(",");
    HttpHost[] httpHosts = new HttpHost[hosts.length];

    for (int i = 0; i < hosts.length; i++) {
        String[] hostAndPort = hosts[i].split(":");
        String host = hostAndPort[0];
        int port = Integer.parseInt(hostAndPort[1]);
        httpHosts[i] = new HttpHost(host, port, "http");
    }

    RestHighLevelClient client = new RestHighLevelClient(
            RestClient.builder(httpHosts));
    return client;
}

查询

需求

实现如下查询:


GET /disease/_search
{
  "_source": {
        "includes": [ "disease_*", "info" ],
        "excludes": [ "" ]
  },
  "query": {
    "bool": {
      "filter": [
        {
          "range": {
            "high_age": {
              "gte": 10
            }
          }
        },
        {
          "range": {
            "low_age": {
              "lte": 10
            }
          }
        }
      ],
      "should": [
        {
          "match": {
            "all_info": """ 恶心["空腹"] 头晕 次数["以上都不是"] 呕吐["清晨"] 呕吐["呕吐后干呕不止"] 呕吐["特定情况下会呕吐"] 腹股沟肿物["鸡蛋大小"] 腹痛["吃东西时"] 腹痛["上腹"] 腹痛["绞痛"] 腹痛["特定情况下会疼痛"] 腹痛["暴饮暴食"] 大便["鲜血便"] 腹泻频繁["特定情况下会腹泻"] 腹泻时间["吃东西时"]"""
          }
        }
      ],
      "must_not": [
        {
          "match": {
            "symptoms": ""
          }
        },
        {
          "match_phrase": {
            "gender": "0"
          }
        },
        {
          "match_phrase": {
            "pregnancy_flag": "1"
          }
        }
      ],
      "must": [
        {
          "match": {
            "symptoms": " 恶心 头晕 恶心与呕吐 发热 腹股沟淋巴结肿大 腹痛 打嗝 稀便"
          }
        }
      ]
    }
  }
}

对应java代码

@Test
public void test() throws IOException {
    SearchRequest request = new SearchRequest();
    request.indices("disease");

    SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
    // 分页所需参数
    sourceBuilder.size(3);
    sourceBuilder.from(0);
    // 过滤字段
    // 第一个参数是要查询的字段,第二个参数是要过滤掉的字段
	sourceBuilder.fetchSource(new String[]{"disease_*""info"}, new String[]{});

    BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();

    boolQueryBuilder.filter(QueryBuilders.rangeQuery("low_age").gte(10));
    boolQueryBuilder.filter(QueryBuilders.rangeQuery("high_age").gte(10));

    boolQueryBuilder.should(QueryBuilders.matchQuery("all_info", "恶心[\"空腹\"]"));

    boolQueryBuilder.mustNot(QueryBuilders.matchQuery("symptoms", "咳嗽"));
    boolQueryBuilder.mustNot(QueryBuilders.matchPhraseQuery("gender", 0));
    boolQueryBuilder.mustNot(QueryBuilders.matchPhraseQuery("pregnancy_flag", 1));

    boolQueryBuilder.must(QueryBuilders.matchQuery("symptoms", "恶心 头晕 恶心与呕吐 发热 腹股沟淋巴结肿大 腹痛 打嗝 稀便"));

    sourceBuilder.query(boolQueryBuilder);

    request.source(sourceBuilder);

    SearchResponse response = client.search(request, RequestOptions.DEFAULT);
    SearchHit[] hits = response.getHits().getHits();
    System.out.println(hits.length);
    for (int i = 0; i < hits.length; i++) {
        SearchHit hit = hits[i];
        System.out.println(hit.getScore());
        System.out.println(hit.getSourceAsString());
    }
}

插入

@Test
public void addDoc() throws IOException {
    IndexRequest request = new IndexRequest("index_member1");
    request.id("1");
    JSONObject params = new JSONObject();
    params.put("username", "zs");
    params.put("password", "bicon@123");
    params.put("birthday", 1588147160000L);
    params.put("height", 175);
    params.put("gender", 0);
    request.source(params, XContentType.JSON);
    IndexResponse response = client.index(request, RequestOptions.DEFAULT);
    int status = response.status().getStatus();
    System.out.println(response);
    System.out.println(status);
}

更新

更新的时候对于没有传入的字段,不做处理。如果想把字段置为null,则需要传入字段名=null

@Test
public void updateIndex() throws IOException {
    UpdateRequest request = new UpdateRequest();
    request.index("index_member1");
    request.id("1");
    JSONObject params = new JSONObject();
    params.put("username", "ls");
    params.put("password", "bicon@1234");
    params.put("birthday", null);
    request.doc(params, XContentType.JSON);
    UpdateResponse response = client.update(request, RequestOptions.DEFAULT);
    System.out.println(response);
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值