使用Nest搜索文本时遇类型转换错误:string无法转为IEnumerable<string>
解决Nest中AnalyzeRequest赋值时的类型转换错误
你遇到的错误“Cannot implicitly convert type 'string' to 'System.Collections.Generic.IEnumerableAnalyzeRequest的Text属性要求传入IEnumerable<string>类型(字符串集合),但你直接传了单个字符串变量**。
修复方案
把单个字符串包装成集合类型即可,比如用数组或者List:
方式1:使用数组
var analyzeResponse = client.Indices.Analyze(new AnalyzeRequest { Text = new[] { text }, // 用数组包装单个字符串 Analyzer = "standard", Tokenizer = "standard" });
方式2:使用List
var analyzeResponse = client.Indices.Analyze(new AnalyzeRequest { Text = new List<string> { text }, // 用List包装单个字符串 Analyzer = "standard", Tokenizer = "standard" });
修正后的完整代码
另外注意原代码中stemCounts定义末尾缺失分号,一并修正:
class Program { static void Main(string[] args) { var settings = new ConnectionSettings(new Uri("http://localhost:9200")) .DefaultIndex("my_index"); var client = new ElasticClient(settings); var text = "testinsg, test, my testing"; var analyzeResponse = client.Indices.Analyze(new AnalyzeRequest { Text = new[] { text }, Analyzer = "standard", Tokenizer = "standard" }); var stemmedWords = analyzeResponse.Tokens.Select(t => t.Token); var stemCounts = stemmedWords .GroupBy(w => new Stemmer().Stem(w)) .Select(g => new { Stem = g.Key, Count = g.Count() }); // 补充缺失的分号 foreach (var stemCount in stemCounts) { Console.WriteLine($"Stem: {stemCount.Stem}, Count: {stemCount.Count}"); } } }
补充说明
Nest设计AnalyzeRequest.Text为集合类型,是为了支持同时分析多个文本内容。哪怕只需要分析一个文本,也必须传入集合形式的值,不能直接传单个字符串。
内容的提问来源于stack exchange,提问作者Eric Mbiada
相关产品推荐
相关产品推荐

