如何解决在 C# 中使用 NEST 库调用 elasticsearch 时如何向 linq 语句添加条件逻辑?
我正在尝试在 C# 中使用流畅的 LINQ 来使用 .NET NEST library 查询 Elasticsearch 服务器。
我想根据传入的搜索请求构建 LINQ 语句。如果搜索请求有价格范围,我想在 Elasticsearch 请求中添加一个范围子句。这是我的代码
var products = await client.SearchAsync<Product>(x =>
{
x = x.Query(q =>
{
if (request.IsAvailable.HasValue)
{
// this gets called,but it is never added to the final elasticsearch call.
q = q.Match(b => b.Field(bm => bm.IsAvailable).Query(request.IsAvailable.Value ? "true" : "false")) as QueryContainerDescriptor<Product>;
}
if (request.MinPrice.HasValue || request.MaxPrice.HasValue)
{
// this gets called,but it is never added to the final elasticsearch call.
q = q.Range(r =>
{
if (request.MinPrice.HasValue)
{
r = r.Field(x => x.Price).GreaterThanorEquals(request.MinPrice.Value);
}
if (request.MaxPrice.HasValue)
{
r = r.Field(x => x.Price).LessthanorEquals(request.MaxPrice.Value);
}
return r;
}) as QueryContainerDescriptor<Product>;
}
if (request.Types != null && request.Types.Length > 0)
{
// this gets called,but it is never added to the final elasticsearch call.
q = q.Terms(t => t.Field(f => f.Type).Terms(request.Types)) as QueryContainerDescriptor<Product>;
}
return q;
});
x = x.source(s => s.Excludes(se =>
{
// This works! There fields are being excluded as expected
if (request.ExcludeSummary)
{
se = se.Field(sef => sef.Summary);
}
if (request.ExcludeTimestamp)
{
se = se.Field(sef => sef.Timestamp);
}
if (request.ExcludeLabels)
{
se = se.Field(sef => sef.Labels);
}
if (request.ExcludeTags)
{
se = se.Field(sef => sef.Tags);
}
return se;
}));
return x;
});
我在 Query()
中的所有条件都没有添加到 elasticsearch 请求中。这意味着生成的 json 请求没有价格或 IsAvaliable 子句。我怀疑演员是罪魁祸首,但不知道如何解决。
Source()
按预期工作。它将正确的字段添加到 excludes
列表中。
解决方法
我发现了这个问题。似乎 NEST 取了最后一个子句,而忽略了前面的所有子句。
这是我为修复它所做的
var products = await client.SearchAsync<Product>(x =>
{
x = x.Query(q =>
{
QueryContainer qc = q;
if (request.IsAvailable.HasValue)
{
qc = qc && +q.Match(b => b.Field(bm => bm.IsAvailable).Query(request.IsAvailable.Value ? "true" : "false"));
}
if (request.MinPrice.HasValue || request.MaxPrice.HasValue)
{
qc = qc && +q.Range(r =>
{
if (request.MinPrice.HasValue)
{
r = r.Field(x => x.Price).GreaterThanOrEquals(request.MinPrice.Value);
}
if (request.MaxPrice.HasValue)
{
r = r.Field(x => x.Price).LessThanOrEquals(request.MaxPrice.Value);
}
return r;
});
}
if (request.Types != null && request.Types.Length > 0)
{
qc = qc && +q.Terms(t => t.Field(f => f.Type).Terms(request.Types));
}
return qc;
});
x = x.Source(s => s.Excludes(se =>
{
if (request.ExcludeSummary)
{
se = se.Field(sef => sef.Summary);
}
if (request.ExcludeTimestamp)
{
se = se.Field(sef => sef.Timestamp);
}
if (request.ExcludeLabels)
{
se = se.Field(sef => sef.Labels);
}
if (request.ExcludeTags)
{
se = se.Field(sef => sef.Tags);
}
return se;
}));
return x;
});
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。