I'm using NEST for ES in .net
This is how im indexing a doc. (Wrote all the elastic client connections in a different class called Settings)
so on a button click
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();
process(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;
}
}
In the above code, when i run the code in debug mode, I'm getting a successful post message with query result(for eg. max_Score = 0.28) where as if i run the code in browser mode, it is still making a call to ES , but the result is empty(max_score =""). I dont know why is this happening. someone please help in solving this.
thanks in advance
A few observations:
"Answer"
as the field name for thematch_phrase
query in your json but NEST by default will camel case all CLR property names when mapping, indexing, searching, etc. This should be"answer"
or change the default field name inference on Connection Settingsmatch_phrase
query,max_score
will benull
so you will need to handle this case. In your example, aslop
of 3 produces no hits for the query somax_score
isnull
. If you changeslop
to 5, you get the document back and a value formax_score
.An example
Writes out the following to the console