简体   繁体   English

如何在带有Nest的Elasticsearch查询中比较文档的两个属性的十进制值?

[英]How to compare decimal values of two properties of a document in an Elasticsearch query with Nest?

I have documents typed product indexed in elasticsearch index. 我有键入在Elasticsearch索引中索引的产品的文档。

These product documents have 2 decimal values: NormalPrice , DiscountPrice . 这些产品文档具有2个十进制值: NormalPriceDiscountPrice

I want to search documents which have NormalPrice > DiscountPrice . 我想搜索具有NormalPrice > DiscountPrice文档。

I tried to construct a query like this: 我试图构造这样的查询:

q &= Query<ProductModel>.Range(u => u.Field(f => f.NormalPrice).GreaterThan(u.Field(f => f.DiscountPrice)));

First of all I'm not sure if my query is correct but if it is, GreaterThan function requires double values as I see. 首先,我不确定查询是否正确,但是如我GreaterThanGreaterThan函数需要双GreaterThan值。

What should I do? 我该怎么办? Is there an alternative way of doing this comparison with decimal values? 是否有其他方法可以与十进制值进行此比较?

BTW changing property types to double is not an option. BTW不能将属性类型更改为double。 I have to use decimal. 我必须使用十进制。

Elasticsearch supports long , integer , short , byte , double and float numeric data types , so NEST maps decimal types to double by default. Elasticsearch支持longintegershortbytedoublefloat数值数据类型 ,因此NEST默认将decimal类型映射为double

To perform a comparison across document fields can be achieved with a script query 通过script查询可以实现跨文档字段的比较

client.Search<ProductModel>(s => s
    .Query(q => q
        .Script(sn => sn
            .Inline("doc['normalPrice'].value > doc['discountPrice'].value")
        )
    )
);

Bear in mind that script queries can be expensive and potentially much slower than other queries depending on what you're doing. 请记住, script查询可能比其他查询昂贵,并且速度可能慢得多,具体取决于您在做什么。 If this is a query that you need to run a lot, you might consider storing the comparison as a boolean field in the document and setting it up as a Property on your ProductModel type 如果这是一个需要大量运行的查询,则可以考虑将比较存储为文档中的布尔值字段并将其设置为ProductModel类型的Property

public class ProductModel
{
    public decimal NormalPrice { get; set:}
    public decimal DiscountPrice { get; set:}
    public bool NormalPriceGreaterThanDiscountPrice 
    { 
        get { return NormalPrice > DiscountPrice; } 
    }
}

and then querying on that. 然后对此进行查询。

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

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