Per creare un indice con nido è semplice come
var client = new ElasticClient();
client.CreateIndex("index-name");
Ciò creerà un indice con il numero predefinito di frammenti e repliche definiti per il nodo.
Per indicizzare un documento rappresentato come JSON nell'indice sarebbe
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);
Qui si usa il client di basso livello per indicizzare JSON, disponibile in NEST tramite la proprietà .LowLevel
su ElasticClient
.
Per cercare il documento indicizzato sarebbe
// 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")
)
)
);
Ciò restituisce il documento indicizzato. Il parametro di tipo generico dynamic
utilizzato in Search<T>()
qui significa che i documenti risultanti verranno deserializzati ai tipi di Json.Net JObject
.
Quando abbiamo creato l'indice, non abbiamo specificato una mappatura per il nostro tipo, type-name
, quindi Elasticsearch ha inferito il mapping dalla struttura del documento json. This is dynamic mapping e può essere utile per molte situazioni, tuttavia, se si conosce la struttura dei documenti che si invierà e non verrà modificata in modo distruttivo, sarà possibile effettuare il specify a mapping for the type. Il vantaggio di fare questo in questo particolare esempio è che la matrice chapter
sarà dedotta come una mappatura object
type, ma se si desidera eseguire la ricerca tra il nome del capitolo e la descrizione del capitolo di un singolo capitolo, probabilmente si desidera mappare come nested
type .
https://github.com/elastic/elasticsearch-net/issues/336 –