【问题标题】:Elasticsearch - how to get the lowest price for a given date rangeElasticsearch - 如何获得给定日期范围内的最低价格
【发布时间】:2017-01-26 13:53:01
【问题描述】:

我正在开发酒店预订应用程序,需要显示低价日历。

我创建了一个这样的 Price 类:

public class Price
{
    public string Id { get; set; }
    public int CityId { get; set; }
    public int HotelId { get; set; }
    public double Value { get; set; }
    public DateTime Date { get; set; }
}

现在想获得给定城市的最低价格。 我尝试过这样的事情:

var result = client.Search<Price>(s => s
    .Skip(0)
    .Take(1000)
    .Query(q => q
        .Bool(b => b
            .Must(
                m => m.Term(t => t.CityId, cityId),
                m => m.DateRange(r => r.Field(rf => rf.Date).GreaterThanOrEquals(startDate).LessThanOrEquals(endDate))))));

问题是,如果城里有几家酒店,我每天会得到不止一个价格。

这是一个例子:

Id = 1
CityId = 1
HotelId = 1
Value = 100
Date = 2017-01-25

Id = 2
CityId = 1
HotelId = 2
Value = 200
Date = 2017-01-25

Id = 3
CityId = 1
HotelId = 1
Value = 400
Date = 2017-01-26

Id = 4
CityId = 1
HotelId = 2
Value = 300
Date = 2017-01-26

如果我发送以下请求:

cityId = 1
startDate = 2017-01-25
endDate = 2017-01-26

我的查询将返回文档 1、2、3 和 4。
但我只想退回文件 1 和 4。
(100是2017-01-25最低价,300是2017-01-26最低价)

任何帮助将不胜感激!

【问题讨论】:

  • 您是否尝试过使用聚合,特别是最小聚合? elastic.co/guide/en/elasticsearch/client/net-api/1.x/…
  • 我尝试添加 .Aggregations(a => a.Min("min_price", ma => ma.Field(p => p.Value))) ,但这只给了我一个聚合(总最低价)。我需要每天的最低价格,而不是整个结果集的最低价格。
  • 您需要将 DateHistogram 聚合与 Min 子聚合一起使用,这样您每天都会得到您期望的结果。

标签: c# elasticsearch nest


【解决方案1】:

我没有太多关于嵌套及其语法的工作知识。所以我会尝试给你原生 ES 查询,你以后可以在嵌套上解决它。

{
    "aggs": {
        "date_histogram": {
            "date_histogram": {
                "field": "Date",
                "interval": "day"
            },
            "aggs": {
                "min_per_day": {
                    "min": {
                        "field": "Value"
                    }
                }
            }
        }
    },
    "query": {
        "bool": {
            "must": [{
                "term": {
                    "cityId": {
                        "value": 2
                    }
                }
            }, {
                "range": {
                    "Date": {
                        "gte": 10,
                        "lte": 20
                    }
                }
            }]
        }
    }
}

添加一个以一天为间隔的日期直方图,并进一步评估聚合值字段的最小值。

谢谢

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-05-08
    • 1970-01-01
    • 1970-01-01
    • 2016-06-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多