是否可以通过查询更新嵌套字段?

时间:2015-04-30 07:01:13

标签: elasticsearch

我正在使用查询插件更新(https://github.com/yakaz/elasticsearch-action-updatebyquery/)来按查询更新文档。 在我的例子中,文档中有嵌套字段,映射是这样的:

"mappings": {
  "mytype": {
    "properties": {
      "Myfield1": {
        "type": "nested",
        "properties": {
          "field1": {
            "type": "string"
          },
          "field2": {
            "type": "long"
          }
        }
      },
      "Title": {
        "type": "string"
      }
    }
  }
}

然后我想通过查询用以下请求更新嵌套字段Myfield1

但不幸的是,它不起作用。

{
  "query": {
    "match": {
      "Title": "elasticsearch"
    }
  },
  "script": "ctx._source.Myfield1 = [{'nestfield1':'foo blabla...','nestfield2':100},{'nestfield1':'abc...','nestfield2':200}]"
}

按查询更新是否支持嵌套对象?

BTW:通过查询更新文档的任何其他方法?

查询插件的更新是唯一的选择吗?

3 个答案:

答案 0 :(得分:0)

您可以尝试params,例如:

"query" : {
    "match_all" : {}
},
"script" : "ctx._source.Myfield1 = Myfield1;",
"params": {
  "Myfield1": {
    "nestfield1": "foo blabla..."
  }
}

在我的情况下,我从嵌套字段中的非嵌套字段移动数据。我需要添加虚假信息来初始化嵌套字段。它看起来像是:

"query" : {
    "match_all" : {}
},
"script" : "ctx._source.Myfield1 = Myfield1; ctx._source.Myfield1.nestfield1 = ctx._source.Myfield1Nestfield1;  ctx._source.Myfield1.nestfield2 = ctx._source.Myfield1Nestfield2;",
"params": {
  "Myfield1": {
    "nestfield1": "init_data"
  }
}

答案 1 :(得分:0)

此示例使用_update_by_query

String name = "";
while (name.trim().length() == 0) {
    System.out.print("Name of the Story Arc:  ");
    name = in.nextLine();
}

int l = 0;
boolean valid = false;
while (!valid) {
    try {
        System.out.print("Length of the Story Arc:  ");
        l = in.nextInt();
        valid = (l > 0);
    } catch (Exception e) {
        e.printStackTrace();
    }
}

答案 2 :(得分:0)

嵌套元素需要在无痛脚本中进行迭代以更新值

    var jObj = JObject.Parse(jsonText);
    var varData = jObj
        .Children<JProperty>()
        .Where(p => p.Name  != "starttime" && p.Name  != "endtime")
        .ToDictionary(x=> x.Name, x => ((JObject)x.Value).ToObject<VarObject>());

如果索引已知,则嵌套元素的值会更新

POST /index/_update_by_query
{
  "script": {
    "source": "for(int i=0;i<=ctx._source['Myfield1'].size()-1;i++){ctx._source.Myfield1[i].field1='foo blabla...';ctx._source.Myfield1[i].field2=100}",
    "lang": "painless"
  },
  "query": {
     "match": {
        "Title": "elasticsearch"
     }
  }
}