First time using ElasticSearch (using NEST as the wrapper). I want to search in an external ElasticSearch database.
I simply want to run a test query towards a specific field called cvrNummer
. I have the following code, which doesn't compile because: The type arguments for method 'ElasticSearch.Search<T> .. ', cannot be inferred from the usage.
I assume it's because I cannot specify the type-specific class. Challenge is I don't know that one.
My question is: how do I run the query below, without exactly know what I get back (to make a type-specific model)? And if I need that model, how do I "make" that model when the documentation is lacking?
My code:
var settings = new ConnectionSettings(new Uri(_path)).
BasicAuthentication(_username,_password);
var client = new ElasticClient(settings);
var es_query = new TermsQuery
{
Name = "named_query",
Boost = 1.1,
Field = "cvrNummer",
Terms = new string[] { "36406208" }
};
client.Search(es_query);
Only documentation I have:
curl -u "<brugernavn>:<password>" -XPOST http://URL -d'
{ "from" : 0, "size" : 1,
"query": {
"term": {
"cvrNummer": VALUE
}
}
}
EDIT MORE DATA:
Document model from documentation:
curl -u "<brugernavn>:<password>" -XGET http://distribution.virk.dk/cvr-permanent/_mapping
Full search example:
curl -u "<brugernavn>:<password>" -XPOST http://distribution.virk.dk/cvr-permanent/_search -d'
{ "from" : 0, "size" : 1,
"query": {
"term": {
"cvrNummer": 10961211
}
}
}
'
You can convert your "documentation" curl request to C# api syntax like this:
client.Search<dynamic>(s => s //dynamic because you don't know the structure
.From(0)
.Size(1)
.Index("cvr-permanent") // index you are searching, taken from url of curl
.AllTypes() // search all types in that index
.Query(q => q.Terms(t =>
t.Name("named_query")
.Boost(1.1f)
.Field("cvrNummer")
.Terms("36406208"))));
If you don't like dynamic
- you can use JObject
, which will be the real type returned by Search
if you used dynamic
:
var response = client.Search<JObject>(...);
Then you can access matched documents like this:
foreach (var document in result.Documents) {
// if you used `JObject`:
Console.WriteLine(document["account_number"]);
// if you used `dynamic`:
Console.WriteLine(document.account_number);
}
If you used JObject
you can also call ToString()
on the resulting JObject
(so, document.ToString()
in the example above) to see full json of returned document, so that you can learn its structure.