【ElasticSearch Nest】调试、单元测试、索引名称推断

索引名称推断

//索引名推断的3种方式
{
    var connectionSettings = new ConnectionSettings(new Uri("http://123.56.57.211:9200"));
    //方式1、默认索引库
    connectionSettings.DefaultIndex("index1");//默认索引库
    //方式2、为.NET类显示指定索引
    connectionSettings.DefaultMappingFor<People>(m => m.IndexName("index2"));//People类型对应索引库index2
    connectionSettings.DefaultMappingFor<People3>(m => m.IndexName("index5"));//People3类型对应索引库index5
    //方式3、请求时指定索引
    var elasticClient = new ElasticClient(connectionSettings);
    elasticClient.Search<People>(q => q.Index("index1"));//查询
    client.Index(data,o=>o.Index("index1"));  //添加

    var searchResponse = elasticClient.Search<People>();//查询index2数据库
    var searchResponse2 = elasticClient.Search<People2>();//查询index5数据库
    var searchResponse3 = elasticClient.Search<People2>();//查询默认数据库index1
}

调试

本地debug时 可以通过fiddler抓取到请求es服务的http请求。也可以在代码中抓取到request和response

第一种方式

var settings = new ConnectionSettings(pool);
//在创建client时开启设置;
//正式环境建议关闭,占用资源
settings.DisableDirectStreaming(true);
var client=new ElasticClient(settings);

var result=client.Search(....);

var requestStr = System.Text.Encoding.Default.GetString(result.ApiCall.RequestBodyInBytes);
var responseStr = System.Text.Encoding.Default.GetString(result.ApiCall.ResponseBodyInBytes);
_log.Debug(requestStr + "                " + responseStr);

第二种方式

        settings.EnableDebugMode((apiCallDetails) =>
        {
            //请求完成 返回 apiCallDetails
            var url = apiCallDetails.Uri.ToString();
            var method = apiCallDetails.HttpMethod.ToString();
            var code = apiCallDetails.HttpStatusCode;
            var requestStr = System.Text.Encoding.Default.GetString(apiCallDetails.RequestBodyInBytes);
            var responseStr = System.Text.Encoding.Default.GetString(apiCallDetails.ResponseBodyInBytes);
        });

第三种方式

        settings.OnRequestCompleted(apiCallDetails =>
        {
            //请求完成 返回 apiCallDetails
            var requestStr = System.Text.Encoding.Default.GetString(apiCallDetails.RequestBodyInBytes);
            var responseStr = System.Text.Encoding.Default.GetString(apiCallDetails.ResponseBodyInBytes);

        });

requestStr:

{
    "from":0,
    "query":{
        "bool":{
            "must":[
                {
                    "term":{
                        "SPUID":{
                            "value":"100308"
                        }
                    }
                },
                {
                    "bool":{
                        "should":[
                            {
                                "match":{
                                    "Title":{
                                        "query":"test1"
                                    }
                                }
                            },
                            {
                                "match":{
                                    "Handle":{
                                        "query":"test1"
                                    }
                                }
                            }
                        ]
                    }
                },
                {
                    "match":{
                        "Description":{
                            "query":"a"
                        }
                    }
                }
            ],
            "must_not":[
                {
                    "term":{
                        "State":{
                            "value":-1
                        }
                    }
                }
            ]
        }
    },
    "size":10,
    "sort":[
        {
            "UpdateTime":{
                "order":"desc"
            }
        }
    ],
    "_source":{
        "includes":[
            "SPUID",
            "Title"
        ]
    }
}

responseStr:

{
    "took":0,
    "timed_out":false,
    "_shards":{
        "total":1,
        "successful":1,
        "skipped":0,
        "failed":0
    },
    "hits":{
        "total":{
            "value":0,
            "relation":"eq"
        },
        "max_score":null,
        "hits":[

        ]
    }
}

单元测试

InMemoryConnection是内置的IConnection,可以轻松地对单元测试进行编写。 它可以配置为使用默认响应字节,HTTP状态代码和进行通话时发生异常进行响应。
InMemoryConnection实际上并不发送任何请求或从Elasticsearch收到任何响应; 请求仍然被序列化,并且如果在请求或全局上将.DisableDirectStreaming设置为true,则可以在响应上获取请求字节

    var responseObj = new
    {
        took = 1,
        timed_out = false,
        _shards = new
        {
            total = 2,
            successful = 2,
            failed = 0
        },
        hits = new
        {
            total = 25,
            max_score = 1.0,
            hits = Enumerable.Range(1, 25).Select(i => (object)new
            {
                _index = "index1",
                _type = "_doc",
                _id = $"{i}",
                _score = 1.0,
                _source = new { Title = $"title {i}" }
            }).ToArray()
        }
    };

    var responseBytes = Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(responseObj));
    var connection = new InMemoryConnection(responseBytes, 200);//始终返回200HTTP状态代码
    var connectionPool = new SingleNodeConnectionPool(new Uri("http://localhost:9200"));
    var settings = new ConnectionSettings(connectionPool, connection).DefaultIndex("index1").DefaultFieldNameInferrer((name) => name).DisableDirectStreaming(true);
    var client = new ElasticClient(settings);
    var response = client.Search<ElasticSpuModel>(s => s.MatchAll());


    var requestStr = System.Text.Encoding.Default.GetString(response.ApiCall.RequestBodyInBytes);
    var responseStr = System.Text.Encoding.Default.GetString(response.ApiCall.ResponseBodyInBytes);
posted @ 2022-06-11 00:47  .Neterr  阅读(81)  评论(0编辑  收藏  举报