如何划分两个领域并求平均值

时间:2019-03-21 18:13:52

标签: elasticsearch

我正在使用Elastic 6.5

我需要将两个字段除以一个平均值。

我要重新创建的示例mysql:

SELECT avg(field1/field2)
FROM table
WHERE field1 > 0 && field2 > 0

2 个答案:

答案 0 :(得分:1)

我已经通过以下查询解决了我的任务:

{
  "size": 0,
  "query": { 
    "match_all":{}
  },
  "aggs": {
    "average": {
      "avg": {
        "script": {
          "source": "(doc['field1'].empty || doc['field2'].empty || doc['field2'].value < 1  ? null : doc['field1'].value / doc['field2'].value)"
        }
      }
    }
  }
}

答案 1 :(得分:0)

您可以使用Script Fields实现所需的功能。

我为此示例创建了示例映射,文档,查询和响应:

映射

PUT myindex
{  
   "mappings":{  
      "mydocs":{  
         "properties":{  
            "field1":{  
               "type":"long"
            },
            "field2":{  
               "type":"long"
            }
         }
      }
   }
}

样本文档:

POST myindex/mydocs/1
{
  "field1": 0,
  "field2": 0
}
POST myindex/mydocs/2
{
  "field1": 20,
  "field2": 20
}
POST myindex/mydocs/3
{
  "field1": 40,
  "field2": 20
}
POST myindex/mydocs/4
{
  "field1": 40,
  "field2": 0
}

查询请求

POST <your_index_name>/_search
{  
   "_source":"*",
   "query":{  
      "match_all":{  

      }
   },
   "script_fields":{  
      "average":{  
         "script":"long a1 = 0l;long a2 = 0l;if(params._source.field1==null){a1 = 01;} else {a1 = params._source.field1}if(params._source.field2==null || params._source.field2<0){ a2=0l} else {a2 = params._source.field2}return a2 > 0? (a1/a2) : 0;"
      }
   }
}

请注意,您可以相应地修改上述逻辑,以适合仅在fields > 0情况下进行平均的用例。

响应

{
  "took": 12,
  "timed_out": false,
  "_shards": {
    "total": 5,
    "successful": 5,
    "failed": 0
  },
  "hits": {
    "total": 4,
    "max_score": 1,
    "hits": [
      {
        "_index": "myindex",
        "_type": "mydocs",
        "_id": "2",
        "_score": 1,
        "_source": {
          "field1": 20,
          "field2": 20
        },
        "fields": {
          "average": [
            1
          ]
        }
      },
      {
        "_index": "myindex",
        "_type": "mydocs",
        "_id": "4",
        "_score": 1,
        "_source": {
          "field1": 40,
          "field2": 0
        },
        "fields": {
          "average": [
            0
          ]
        }
      },
      {
        "_index": "myindex",
        "_type": "mydocs",
        "_id": "1",
        "_score": 1,
        "_source": {
          "field1": 0,
          "field2": 0
        },
        "fields": {
          "average": [
            0
          ]
        }
      },
      {
        "_index": "myindex",
        "_type": "mydocs",
        "_id": "3",
        "_score": 1,
        "_source": {
          "field1": 40,
          "field2": 20
        },
        "fields": {
          "average": [
            2
          ]
        }
      }
    ]
  }
}

您在上述响应中寻找的是average字段。

希望有帮助!