elasticsearch,Node.js,elasticsearch" /> elasticsearch,Node.js,elasticsearch" />

Node.js 如何根据聚合结果进行计算?

Node.js 如何根据聚合结果进行计算?,node.js,elasticsearch,Node.js,elasticsearch,例如,我可以根据父id获得特定url的请求平均计数结果,代码如下: client.search({ index: 'console-*', body: { query: { bool: { query_string: { query: 'meta.http.url:"https://www.google.com"' } } }, aggs: { parent_id: {

例如,我可以根据父id获得特定url的请求平均计数结果,代码如下:

client.search({
  index: 'console-*',
  body: {
    query: {
      bool: {
        query_string: {
          query: 'meta.http.url:"https://www.google.com"'
        }
      }
    },
    aggs: {
      parent_id: {
        terms: {
          field: 'parent_id'
        }
      }
    }
  },
  size: 0
}).then(res => {
  console.log(res.hits.total/res.aggregations.total.value)
})
现在让我们假设我有许多URL,如:

https://www.google.com
https://www.bing.com
https://www.apple.com
我可以使用:

client.search({
  index: 'console-*',
  body: {
    sort: {
      '@timestamp': {
        order: 'asc'
      }
    },
    query: {
      bool: {
        must: [{
          range: {
            '@timestamp': {
              gte: 'now-5m',
              lte: 'now'
            }
          }
        }, {
          query_string: { query: '_exists_:meta.http.url' }
        }]
      }
    },
    aggs: {
      urls: {
        terms: {
          field: 'meta.http.url'
        },
        aggs: {
          total: {
            cardinality: {
              field: 'parent_id'
            }
          }
        }
      }
    }
  },
  size: 0
}).then(res => {
  console.log(JSON.stringify(res))
  console.log(res.aggregations.urls.buckets.map(o => {
    const res = {};
    res[o.key] = o.doc_count / o.total.value;
    return res;
  }))
})

不在Node.js中进行任何额外的计算就可以得到结果吗?

是的,您可以利用管道聚合,更具体地说,是

aggs
部分看起来是这样的,在每个bucket中,您将得到文档计数的结果除以
compute
部分中存储的总值:

aggs: {
  urls: {
    terms: {
      field: 'meta.http.url'
    },
    aggs: {
      total: {
        cardinality: {
          field: 'parent_id'
        }
      },
      compute: {
        bucket_script: {
          buckets_path: {
            count: "_count",
            total: "total"
          },
          script: "params.count / params.total"
        }
      }
    }
  }
}

非常感谢。在路径中_count和total是什么意思?它们不应该是“doc\u count”和“total.value”吗?我还收到了错误:
{“error”:{“root\u cause”:[],“type”:“search\u phase\u execution\u exception”,“reason”:“,”phase:“fetch”,“grouped”:true,“failed\u shard”:[],“course:”,“course:“{”type:“script\u exception”,“script stack:”[“count/total”,“count/total”,“这里”;“script:“count/total”,“lang”:“无痛”,“原因”:{“类型”:“非法参数”\u异常”,“原因”:“变量[count]未定义”。}}}}},“状态”:503}
抱歉,已修复,请重试{u count和total是什么意思?如果我在其他搜索中使用这个功能,我想知道这些参数是如何工作的。如果你按照我给你的链接,你会看到它是如何工作的
\u count
指存储桶中的文档数(即代码中的
o.doc\u count
),而
total
指代码中名为
total
(即
o.total.value
)的基数聚合值。试试看