gpt4 book ai didi

elasticsearch - Elastic Search NEST客户端原始+自定义查询

转载 作者:行者123 更新时间:2023-12-03 01:20:38 30 4
gpt4 key购买 nike

我正在使用NEST客户端查询ES,但是现在有一种特殊情况-我正在尝试将查询代理到ES,但是默认情况下应用了特定查询:

public IEnumerable<TDocument> Search<TDocument>(string indexName, string query, string sort, int page, int pageSize) where TDocument : class
{
var search = new SearchRequest(indexName)
{
From = page,
Size = pageSize,
Query = new RawQuery(query),
};


var response = this.client.Search<TDocument>(search);

return response.Documents;
}

上面的代码只是将查询代理到ES,但是如果我需要应用应始终与传递的查询一起应用的特定过滤器,该怎么办?

因此,例如,我希望默认情况下 Active字段为 true。如何将这个原始查询与一些特定且始终应用的过滤器合并(如果可能,不合并字符串以制定合并的ES API调用)。

最佳答案

假设query是与查询DSL相对应的格式正确的JSON,则可以将其反序列化为QueryContainer的实例,并将其与其他查询组合。例如

var client = new ElasticClient();

string query = @"{
""multi_match"": {
""query"": ""hello world"",
""fields"": [
""description^2.2"",
""myOtherField^0.3""
]
}
}";

QueryContainer queryContainer = null;

using (var stream = client.ConnectionSettings.MemoryStreamFactory.Create(Encoding.UTF8.GetBytes(query)))
{
queryContainer = client.RequestResponseSerializer.Deserialize<QueryContainer>(stream);
}

queryContainer = queryContainer && +new TermQuery
{
Field = "another_field",
Value = "term"
};

var searchResponse = client.Search<TDocument>(s => s.Query(q => queryContainer));

它将转换为以下查询(假设默认索引为 _all)
POST http://localhost:9200/_all/_search?pretty=true&typed_keys=true 
{
"query": {
"bool": {
"filter": [{
"term": {
"another_field": {
"value": "term"
}
}
}],
"must": [{
"multi_match": {
"fields": ["description^2.2", "myOtherField^0.3"],
"query": "hello world"
}
}]
}
}
}

关于elasticsearch - Elastic Search NEST客户端原始+自定义查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60342402/

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