【问题标题】:How to update an entry on Elastic Search using Java client如何使用 Java 客户端更新 Elastic Search 上的条目
【发布时间】:2023-04-07 04:28:01
【问题描述】:

我正在尝试使用弹性搜索客户端更新我的 es 模型信息

org.elasticsearch.client.Client

https://www.programcreek.com/java-api-examples/?api=org.elasticsearch.client.Client

我真的很难找到正确的方法,因为我不知道索引和匹配器,对不起,我是这个主题的初学者。

  {
    "_index": "my_index_20",
    "_type": "student",
    "_id": "a80ae58",
    "_source": {
      "model": {
        "id": "a80ae58748e",
        "name": "John Doe"
        ....

到目前为止我的代码

 response = esClient.prepareUpdate("student", "name", "John Doe")
                    .setDoc(jsonBuilder()               
                    .startObject()
                    .field("name", "Joe Doe")
                    .endObject())
                    .get();

我是否使用了正确的索引?或者我可以在这里改变什么?

我没有收到任何错误,但“文档丢失”结果...意味着我可能没有使用正确的索引。

想法?

根据反馈和更多信息更新...

我把它移到了

response = esClient.prepareUpdate("my_index_20", "student", "a80ae58")
                    .setDoc(jsonBuilder()               
                    .startObject()
                    .field("name", "Joe Doe")
                    .endObject())
                    .get();

这可行,但由于我不知道索引 ID,我无法执行此操作,是否有任何方法可以通过查询生成器或其他功能来完成?

【问题讨论】:

    标签: java elasticsearch


    【解决方案1】:

    这是 prepareUpdate 方法的签名:

    UpdateRequestBuilder prepareUpdate(String index, String type, String id);
    

    所以正确的语法可能是

    esClient.prepareUpdate("my_index_20", "student", "a80ae58").setDoc(...)...
    

    如果您想通过匹配其他字段来做到这一点,请使用查询更新。

    String indexName = "my_index_*"; //Assuming that you don't know the exact index, but know the global format (for example the beginning of the name of the index)
    BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();
    boolQuery.filter(QueryBuilders.termQuery("name", "John Doe"));
    boolQuery.filter(QueryBuilders.termQuery("otherField", "otherFieldValue"));
    UpdateByQueryRequestBuilder updateByQuery = UpdateByQueryAction.INSTANCE.newRequestBuilder(esClient);
    updateByQuery.source(indexName); 
    updateByQuery.filter(boolQuery); 
    BulkByScrollResponse updateResponse = updateByQuery.get();
    

    【讨论】:

    • 你好,是的,但是我自己没有ID,有没有我可以通过匹配其他字段来做到这一点?
    • 当然。通过查询使用更新。看到这个链接elastic.co/guide/en/elasticsearch/client/java-rest/master/…
    • 知道如何处理这种情况吗? :s 它仍然说我需要索引
    • 如果你不知道确切的索引,但知道全局格式(例如索引名称的开头),你可以这样做:String indexName = "my_index_*"; BoolQueryBuilder boolQuery = QueryBuilders.boolQuery(); boolQuery.filter(QueryBuilders.termQuery("name", "John Doe")); UpdateByQueryRequestBuilder updateByQuery = UpdateByQueryAction.INSTANCE.newRequestBuilder(esClient); updateByQuery.source(indexName); updateByQuery.filter(boolQuery); BulkByScrollResponse updateResponse = updateByQuery.get();
    • @user6441481 你应该用那个代码更新你的答案,它会更清晰
    猜你喜欢
    • 2017-06-01
    • 1970-01-01
    • 2021-01-08
    • 1970-01-01
    • 1970-01-01
    • 2022-11-07
    • 2021-11-14
    • 1970-01-01
    • 2020-03-11
    相关资源
    最近更新 更多