Elastic search filter by the number of attached documents

I have an elastic search index for firms that has a nested object called transactions . There is at least a date in the transaction . Here is an example:

firms: [
  {
    "name": "abc",
    "address" : "xyz",
    "transactions": [
       {
         "date" : "2014-12-20"
         "side" : "buyer"
       },
       ...
     ]
  },
  ...
]

Given this data, I want to request from all firms that have (say) 3+ transactions in the last 6 or 12 months.

The following query returns firms that have at least one transaction in the last 12 months:

POST firms/firm/_search
    {
    "query": {
        "nested": {
           "path": "transactions",
           "query": {
               "bool": {
                   "must": [
                      {
                          "match": {
                             "transactions.side": "buyer"
                          }
                      },
                      {
                          "range": {
                             "transactions.date": {
                                "from": "2014-10-24",
                                "to": "2015-10-24"
                             }
                          }
                      }
                   ]
               }
           }
        }  
    }
}

I am not sure how to expand this query to fit firms with x + transactions in the y + month period. Any help would be appreciated. Thanks

+4
source share
1 answer

, , script. - :

{
  "query": {
    "bool": {
      "must": [
        {
          "nested": {
            "path": "transactions",
            "query": {
              "bool": {
                "must": [
                  {
                    "match": {
                      "transactions.side": "buyer"
                    }
                  },
                  {
                    "range": {
                      "transactions.date": {
                        "from": "2014-10-24",
                        "to": "2015-10-24"
                      }
                    }
                  }
                ]
              }
            }
          }
        },
        {
          "filtered": {
            "filter": {
              "script": {
                "script": "if(_source.transactions.size<3) return false;fromDate=Date.parse('yyyy-MM-dd',fromDateParam);toDate=Date.parse('yyyy-MM-dd',toDateParam);count=0;for(d in _source.transactions){docsDate=Date.parse('yyyy-MM-dd',d.get('date'));if(docsDate>=fromDate && docsDate<=toDate){count++};if(count==3){return true;}};return false;",
                "params": {
                  "fromDateParam":"2014-10-24",
                  "toDateParam":"2015-10-24"
                }
              }
            }
          }
        }
      ]
    }
  }
}

range - "" , . , ( ) script.

script , 3. , false. , 3, . 3, true.

+2

Source: https://habr.com/ru/post/1613006/


All Articles