2015-10-28 72 views
4

我正在尝试在C#中编写用于PUT和GET的代码来获取我的elasticsearch数据。 我输入代码,这样PUT,它似乎是它的工作原理:如何从C#通过HTTP查询Elasticsearch?

string url = "http://localhost:9200/my_index/my_type/"; 

JsonDocFormat json = new JsonDocFormat() 
{ 
    name = "John" 
}; 

string s = JsonConvert.SerializeObject(json); 

using (var client = new WebClient()) 
{ 
    client.UploadString(url, "POST", s); 
} 

但我不能为这个GET写代码:

GET my_index/my_type/_search 
{ 
    "query" : { 
     "match" : { 
      "name" : "john" 
     } 
    } 
} 

我想是这样的:

string url_req = "http://localhost:9200/my_index/my_type/_search?pretty"; 

string s1 = "{\"query\": {\"match\": { \"name\" : \"john\" }}}"; 

string s_req = url_req + s1; 

using (var client = new WebClient()) 
{ 
    Console.Write(client.DownloadString(s_req)); 
} 

但这段代码返回相同的输出作为该GET:

GET /my_index/my_type/_search 

它没有抛出任何错误,但它完全忽略了URL结尾的json body。我想在没有任何外部包(如NEST或Elasticsearch.NET)的情况下编写它,只需使用HTTP。

在此先感谢您的帮助!

+0

不应串S1是 “{\” 查询\ “:{\” 匹配\ “:{\” 名称\ “:\” 约翰\“}}}”? – ChintanShah25

+0

对不起,只是一个错误..我试图让它更容易理解。在我的原始文档中,我使用了'text'字段,但是在这里我将其重命名为'name',但是我忘记在该段代码中覆盖特定的'text'。但是我的问题仍然存在。 – Gondil

回答

0

我的问题最终的解决方案是在此代码

string url_req = "http://localhost:9200/my_index/my_type/_search?pretty"; 

string s = "{\"query\": {\"match\": { \"name\" : \"john\" }}}"; 

using (var client = new WebClient()) 
{ 
    Console.Write(client.UploadString(url_req, "POST", s)); 
}