简体   繁体   English

使用动态字段名称搜索 ElasticSearch

[英]Searching ElasticSearch with dynamic field names

I have a method to search in C# as follows:我有一种在 C# 中搜索的方法如下:

public void Search(string data)
        {
            var searchResponse = client.Search<Products>(s => s
                .From(0)
               .Size(100)
               .Query(q => q
                 .Match(m => m
                     .Field( f => f.ProductName)
                      .Query(data))));
             int cnt = searchResponse.Documents.Count;
        }

This returned 5 documents, which is valid.这返回了 5 个文档,这是有效的。

But, I wanted to modify the above method as follows, so that I can pass the field to be searched dynamically.但是,我想将上述方法修改如下,以便可以动态传递要搜索的字段。

public void Search(string data,string fieldName)

    {
            var searchResponse = client.Search<Products>(s => s
                .From(0)
               .Size(100)
               .Query(q => q
                 .Match(m => m
                     .Field(fieldName)
                      .Query(data))));

            int cnt = searchResponse.Documents.Count;

        }

The above code does return any error, but return 0 documents.上面的代码确实返回了任何错误,但返回了 0 个文档。

Here I am passing ProductName to fieldName parameter.在这里,我将ProductName传递给fieldName参数。 I know this will not work.我知道这行不通。 I just want tell my intention here.我只想在这里说出我的意图。

Field Infering 场推断

You can pass below to your query您可以将以下内容传递给您的查询

var fieldString = new Field("fieldName"); var fieldString = new Field("fieldName");

var fieldString = new Field("fieldName");
var searchResponse = _elasticClient.Search<AllOpportunitySearchResult>(s => s
                                   .From(0)
                                   .Size(100)
                                   .Query(q => q
                                                .Match(m => m
                                                             .Field(fieldString)
                                                             .Query(data)
                                                      )
                                         )
                      );

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

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