To create an index with NEST is as simple as
var client = new ElasticClient();
client.CreateIndex("index-name");
This will create an index with the default number of shards and replicas defined for the node.
To index a document represented as json into the index would be
var json = @"{
""BookName"": ""Book1"",
""ISBN"": ""978-3-16-148410-0"",
""chapter"" : [
{
""chapter_name"": ""Chapter1"",
""chapter_desc"": ""Before getting into computer programming, let us first understand computer programs and what they...""
},
{
""chapter_name"": ""Chapter2"",
""chapter_desc"": ""Today computer programs are being used in almost every field, household, agriculture, medical, entertainment, defense..""
},
{
""chapter_name"": ""Chapter3"",
""chapter_desc"": ""MS Word, MS Excel, Adobe Photoshop, Internet Explorer, Chrome, etc., are...""
},
{
""chapter_name"": ""Chapter4"",
""chapter_desc"": ""Computer programs are being used to develop graphics and special effects in movie...""
}
]
}";
var indexResponse = client.LowLevel.Index<string>("index-name", "type-name", json);
if (!indexResponse.Success)
Console.WriteLine(indexResponse.DebugInformation);
Here we use the low level client to index json, available in NEST through the .LowLevel
property on ElasticClient
.
To search the indexed document would be
// refresh the index so that newly indexed documents are available
// for search without waiting for the refresh interval
client.Refresh("index-name");
var searchResponse = client.Search<dynamic>(s => s
.Index("index-name")
.Type("type-name")
.Query(q => q
.Match(m => m
.Query("Photoshop")
.Field("chapter.chapter_desc")
)
)
);
This returns the document indexed. The generic type parameter dynamic
used in Search<T>()
here means that the resulting documents will be deserialized to Json.Net JObject
types.
When we created the index, we didn't specify a mapping for our type, type-name
, so Elasticsearch inferred the mapping from the structure of the json document. This is dynamic mapping and can be useful for many situations however, if you know the structure of documents that you're going to be sending and it's not going to be destructively changed, then you specify a mapping for the type. The advantage of doing this in this particular example is that the chapter
array will be inferred as an object
type mapping, but if you wanted to search across both chapter name and chapter description of an individual chapter, then you probably want to map chapter
as a nested
type.