gpt4 book ai didi

c# - 使用NEST(ElasticSearch)搜索嵌套数组

转载 作者:行者123 更新时间:2023-12-03 01:14:54 24 4
gpt4 key购买 nike

我想使用Nest过滤嵌套数组中的数据。
鉴于我有以下类(class):

public class Package
{
public IEnumerable<PackageItem> PackageItems { get; set; }
}

public class PackageItem
{
public string Title { get; set; }
public decimal Price { get; set; }
}
并且我使用NEST在ElasticSearch中为这些数据编制了索引:
这是我的数据:
"hits" : [
{
"_index" : "packages",
"_type" : "_doc",
"_id" : "cf08b05c-c8b5-45cb-bca8-17267c3613fb",
"_score" : 1.0,
"_source" : {
"id" : "cf08b05c-c8b5-45cb-bca8-17267c3613fb",
"PackageItems" : [
{
"Title" : "some-title",
"price" : 100000.0
},
{
"Title" : "some-title",
"price" : 200000.0
}
]
}
},
{
"_index" : "packages",
"_type" : "_doc",
"_id" : "39436cb3-483e-4fb4-92e4-4e06ecad27a1",
"_score" : 1.0,
"_source" : {
"id" : "39436cb3-483e-4fb4-92e4-4e06ecad27a1",
"PackageItems" : [
{
"Title" : "some-title",
"price" : 100000.0
},
{
"Title" : "some-title",
"price" : 400000.0
}
]
}
},
{
"_index" : "packages",
"_type" : "_doc",
"_id" : "cd5d3587-838b-46ec-babc-d756c5587396",
"_score" : 1.0,
"_source" : {
"id" : "cd5d3587-838b-46ec-babc-d756c5587396",
"PackageItems" : [
{
"Title" : "some-title",
"price" : 300000.0
},
{
"Title" : "some-title",
"price" : 500000.0
}
]
}
}
]
我想用minimumPackageItemPrice:100000和maximumPackageItemPrice:400000过滤软件包。我应该使用NEST执行什么查询?
结果应该是这样的:
"hits" : [
{
"_index" : "packages",
"_type" : "_doc",
"_id" : "cf08b05c-c8b5-45cb-bca8-17267c3613fb",
"_score" : 1.0,
"_source" : {
"id" : "cf08b05c-c8b5-45cb-bca8-17267c3613fb",
"PackageItems" : [
{
"Title" : "some-title",
"price" : 100000.0
},
{
"Title" : "some-title",
"price" : 200000.0
}
]
}
},
{
"_index" : "inventories",
"_type" : "_doc",
"_id" : "39436cb3-483e-4fb4-92e4-4e06ecad27a1",
"_score" : 1.0,
"_source" : {
"id" : "39436cb3-483e-4fb4-92e4-4e06ecad27a1",
"PackageItems" : [
{
"Title" : "some-title",
"price" : 100000.0
},
{
"Title" : "some-title",
"price" : 400000.0
}
]
}
}
]

最佳答案

要通过NEST在Elasticsearch上触发范围查询,您可以使用范围查询。该方法是您可以为场景构造一个范围查询,并通过NEST客户端的搜索方法触发该查询。
为您的案例生成范围查询

// This method builds the range query where price should be between 
// 100000.0 and 400000.0 (inclusive range in this case)
private static QueryContainer BuildNestedRangeQuery()
{
return new QueryContainerDescriptor<Package>()
.Nested(n =>
n.Path(p => p.PackageItems)
.Query(q => q
.Range(r => r
.Field(f => f.PackageItems.FirstOrDefault().Price)
.GreaterThanOrEquals(100000.0)
.LessThanOrEquals(400000.0))
)
)
)
}
触发搜寻
可以通过 NEST客户端触发搜索,如下所示。这可能会根据您自己的实现而有所不同。但是,上述范围查询保持不变。
// Replace T with type of your choice and client is NEST client
var result = client.Search<T>(
.From(0)
.Size(20)
.Query(q => BuildNestedRangeQuery())
// other methods that you want to chain go here
)

关于c# - 使用NEST(ElasticSearch)搜索嵌套数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63014371/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com