简体   繁体   English

比较2个字段的elasticsearch查询(使用java)

[英]elasticsearch query on comparing 2 fields (using java)

I've an index in my elasticsearch and I want to have a query to compare 2 date fields.我的 elasticsearch 中有一个索引,我想要一个查询来比较 2 个日期字段。 assuming fields name are creationDate and modifiedDate .假设字段名称是creationDatemodifiedDate I want to get all documents which these 2 dates are the same in them.我想获得这两个日期相同的所有文件。

I know it was possible to use FilteredQuery which is deprecated right now.我知道可以使用现在已弃用的FilteredQuery something like the bellowing code:类似于下面的代码:

FilteredQueryBuilder query = QueryBuilders.filteredQuery(null,
    FilterBuilders.scriptFilter("doc['creationDate'].value = doc['modifiedDate'].value"));

Also it's maybe possible to write manual scripts as string, but I doubt that this is the right solution.此外,也可以将手动脚本编写为字符串,但我怀疑这是正确的解决方案。 Any idea's to create the properly query would be appreciated.任何创建正确查询的想法将不胜感激。

Filtered query have been replaced by bool/filter queries You can do it like this:过滤查询已被bool/filter查询取代您可以这样做:

BoolQueryBuilder bqb = QueryBuilders.boolQuery()
    filter(QueryBuilders.scriptQuery("doc['creationDate'].value = doc['modifiedDate'].value"));

However, instead of using scripts at search time, you'd be better off creating a new field at indexing time that contains the information of whether creationDate and modifiedDate are the same dates.但是,与其在搜索时使用脚本,不如在索引时创建一个新字段,其中包含creationDatemodifiedDate是否为同一日期的信息。 Then, you could simply check that flag at query time, it would be much more optimal and fast.然后,您可以在查询时简单地检查该标志,它会更加优化和快速。

If you don't want to reindex all your data, you can update all of them with that flag, simply run an update by query like this:如果您不想重新索引所有数据,您可以使用该标志更新所有数据,只需像这样按查询运行更新:

POST my-index/_update_by_query发布我的索引/_update_by_query

{
  "script": {
    "source": """
    def creationDate = Instant.parse(ctx._source.creationDate);
    def modifiedDate = Instant.parse(ctx._source.modifiedDate);
    ctx._source.modified = ChronoUnit.MICROS.between(creationDate, modifiedDate) > 0;
    """,
    "lang": "painless"
  },
  "query": {
    "match_all": {}
  }
}

And then your query will simply be然后你的查询将只是

BoolQueryBuilder bqb = QueryBuilders.boolQuery()
    filter(QueryBuilders.termQuery("modified", "false");

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM