简体   繁体   English

在嵌套Elasticsearch中使用原始字符串创建查询

[英]Creating query with raw strings in nest elasticsearch

I need to create the query dynamically. 我需要动态创建查询。 I have a list of terms with their weights in a hashtable that the number of terms varies. 我在哈希表中有一个术语列表及其权重,这些术语的数量各不相同。 I want to search these terms in the content of an amount of documents and boost each words according to its weight. 我想在大量文档的内容中搜索这些术语,并根据其权重来增强每个单词。 Something similar to the code below: 类似于以下代码:

var searchResults = client.Search<Document>(s => s.Index(defaultIndex)
 .Query(q => q.Match(m => m.OnField(p => p.File).Query(term1).Boost(term1.weight).Query(term2).Query(term2.weight)...Query(term N ).Boost(termN.weight))))

The only solution that I found is to use "Raw String" like the example in the link http://nest.azurewebsites.net/nest/writing-queries.html 我发现的唯一解决方案是使用“原始字符串”,如链接http://nest.azurewebsites.net/nest/writing-queries.html中的示例

.QueryRaw(@"{""match_all"": {} }")
.FilterRaw(@"{""match_all"": {} }")

Since I don't know how many terms exist each time, how can I handle such a problem? 由于我不知道每次都存在多少个术语,我该如何处理这样的问题? Does anyone know another solution rather than "Raw strings"? 有谁知道其他解决方案,而不是“原始字符串”? I am using C# Nest Elasticsearch. 我正在使用C#Nest Elasticsearch。

Here is a sample of JSON Elasticsearch query for such a case: 这是针对这种情况的JSON Elasticsearch查询示例:

GET  testindex2/document/_search
{
  "query": {
   "bool": {
    "should": [
    {
      "match": {
        "file": {
          "query": "kit",
          "boost": 3
        }
      }
    },
    {
      "match": {
        "file": {
          "query": "motor",
          "boost": 2.05
        }
      }
    },
    {
      "match": {
        "file": {
          "query": "fuel",
          "boost": 1.35
        }
      }
    }
  ]
}

} } }}

You need to create a Bool Should query and pass an array of QueryContainer objects which can be generated dynamically. 您需要创建一个Bool Should查询并传递可以动态生成的QueryContainer对象数组。 I've written a small code snippet that will build the Nest query as per your requirements. 我已经编写了一个小代码段,可以根据您的要求构建Nest查询。 Simply update the Dictionary boostValues and you should be good to go. 只需更新字典boostValues ,就可以了。

var boostValues = new Dictionary<string, double>
{
    { "kit", 3 },
    { "motor", 2.05 },
    { "fuel", 1.35 }
};

var qc = new List<QueryContainer>();
foreach (var term in boostValues)
{
    qc.Add(
        Query<Document>.Match(m => m
            .OnField(p => p.File)
            .Boost(term.Value)
            .Query(term.Key)));
}

var searchResults = client.Search<Document>(s => s
    .Index(defaultIndex)
    .Query(q => q
        .Bool(b => b
            .Should(qc.ToArray()))));

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

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