使用NEST进行弹性搜索 - 在调试和浏览器模式下的结果不同

时间:2016-04-20 02:40:11

标签: c# asp.net elasticsearch nest

我在.net

中使用NEST for ES

这就是我如何编制doc文档。 (在名为Settings的不同类中写了所有弹性客户端连接)

所以点击按钮

client = Settings.connection();
          var res1 = new Class1
            {
                Id = 1,
                Ans = "The quick brown fox jumps over the lazy dog"
            };
    if (client.IndexExists("zzz").Exists == true)
            {
                client.Index(res1);
            }

string ans = getInfo();

处理(ANS);

    public string getInfo(){
        string wordInfoQuery = @"{
                        ""query"": {
                            ""match_phrase"":{
                                ""Answer"":{
                                              ""query"": ""brown dog"",
                                              ""slop"": "3"
                                            }
                                        }
                                    }
                                }";


              try
                        {

                            if (client != null)
                            {
                                var callResult = client.LowLevel.Search<string>(wordInfoQuery);
                                reply = callResult.Body.ToString();
                                e.Write(callResult.Body);
                            }

                        }
                               return reply;
    }

public void process(string answer)
        {

            if (!string.IsNullOrEmpty(answer))
            {
                byte[] byteArray = Encoding.UTF8.GetBytes(answer);
                MemoryStream m = new MemoryStream(byteArray);
                float score;
                using (StreamReader r = new StreamReader(m))
                {
                    string json1 = r.ReadToEnd();
                    JObject jobj1 = JObject.Parse(json1);
                    JToken agg1 = jobj1.GetValue("hits")["max_score"];
                    if (agg1!=null) //getting an error here most of the times. if the max_score field is null (for eg: instead of brown dog if i send "tax" as a query term)
                    {
                        score = agg1.ToObject<float>();
                    }
                    else
                    {
                        score = 0;
                    }

                }

            }

        }

class Settings{
public static ElasticClient connection()
        {
            configvalue1 = ConfigurationManager.AppSettings["url"];//stored the url in web.config (http://localhost:9200)

            node = new Uri(configvalue1);
            settings = new ConnectionSettings(node)
                .DefaultIndex("zzz")
                .MapDefaultTypeNames(m => m.Add(typeof(Class1), "omg"));
            client = new ElasticClient(settings);

            if (client.IndexExists("zzz").Exists)
            {
                client.DeleteIndex("zzz"); //i want to index only one doc at a time. so deleting and creating everytime i click on the button
                client.CreateIndex("zzz");
            }


            return client;
        }
    }

在上面的代码中,当我在调试模式下运行代码时,我获得了一条带有查询结果的成功发布消息(例如,max_Score = 0.28),就好像我在浏览器模式下运行代码一样,仍在调用ES,但结果为空(max_score =&#34;&#34;)。我不知道为什么会这样。 有人请帮忙解决这个问题。

提前致谢

1 个答案:

答案 0 :(得分:1)

一些观察结果:

  1. 您在json中使用"Answer"作为match_phrase查询的字段名称,但默认情况下NEST将在映射,索引,搜索等时使用所有CLR属性名称。这应该是{{ 1}}或change the default field name inference on Connection Settings
  2. 如果"answer"查询没有结果,match_phrase将为max_score,因此您需要处理此案例。在您的示例中,null为3不会对查询产生任何匹配,因此slopmax_score。如果您将null更改为5,则会获得该文档以及slop的值。
  3. 我建议您使用NEST中的Fluent APIObject Initializer Syntax,除非您有充分的理由不这样做(如果您确实有理由,我们很乐意知道!)。 usage examples of all of the Query DSL for NEST 2.x 应该有希望帮助:)
  4. 一个例子

    max_score

    将以下内容写入控制台

    void Main()
    {
        var pool = new SingleNodeConnectionPool(new Uri("http://localhost:9200"));
        var defaultIndex = "zzz";
    
        var connectionSettings = new ConnectionSettings(pool)
                .DefaultIndex(defaultIndex)
                .MapDefaultTypeNames(m => m.Add(typeof(Class1), "omg"))
                .PrettyJson()
                .DisableDirectStreaming()
                .OnRequestCompleted(response =>
                    {
                        // log out the request
                        if (response.RequestBodyInBytes != null)
                        {
                            Console.WriteLine(
                                $"{response.HttpMethod} {response.Uri} \n" +
                                $"{Encoding.UTF8.GetString(response.RequestBodyInBytes)}");
                        }
                        else
                        {
                            Console.WriteLine($"{response.HttpMethod} {response.Uri}");
                        }
    
                        // log out the response
                        if (response.ResponseBodyInBytes != null)
                        {
                            Console.WriteLine($"Status: {response.HttpStatusCode}\n" +
                                     $"{Encoding.UTF8.GetString(response.ResponseBodyInBytes)}\n" +
                                     $"{new string('-', 30)}\n");
                        }
                        else
                        {
                            Console.WriteLine($"Status: {response.HttpStatusCode}\n" +
                                     $"{new string('-', 30)}\n");
                        }
                    });
    
        var client = new ElasticClient(connectionSettings);
    
        if (client.IndexExists(defaultIndex).Exists)
        {
            client.DeleteIndex(defaultIndex);
        }
    
        client.CreateIndex(defaultIndex);
    
        client.Index(new Class1
        {
            Id = 1,
            Answer = "The quick brown fox jumps over the lazy dog"
        }, i => i.Refresh());
    
        var searchResponse = client.Search<Class1>(s => s
            .Query(q => q
                .MatchPhrase(mp => mp
                    .Field(f => f.Answer)
                    .Query("brown dog")
                    .Slop(5)
                )
            )
        );
    
        Console.WriteLine(searchResponse.MaxScore);
    }
    
    public class Class1
    {
        public int Id { get; set; }
        public string Answer { get; set;}
    }