es java 使用script脚本对某个字段做乘积后求和并展示一条文档和多条文档之间的区别

 /**
     * 对某个字段做乘积后求和
     */
    @Test
    public void multi(){
        SearchResponse response = client.prepareSearch(indexName).setTypes(typeName)
                .addAggregation(AggregationBuilders.sum("userAgg")
                        .script(new Script("params._source.age *2")))
                        .get();
        Sum sum = response.getAggregations().get("userAgg");
        System.out.println(sum.getValue());
    }

在上述代码中是对多条文档进行操作,所以使用params._source获取所有文档;
若指定唯一文档,则使用ctx._source获取文档信息;

 /**
     * 指定文档对某字段做乘积后赋值给当前字段
     * @throws ExecutionException
     * @throws InterruptedException
     */
    @Test
    public void script() throws ExecutionException, InterruptedException {
        UpdateRequest updateRequest = new UpdateRequest();
        updateRequest.index(indexName);
        updateRequest.type(typeName);
        updateRequest.id("AWVGha8Jcu8UkN_wpIjN");
        updateRequest.script(new Script("ctx._source.age = ctx._source.age * 2"));
        client.update(updateRequest).get();
    }

猜你喜欢

转载自blog.csdn.net/qq_34624315/article/details/82848508
今日推荐