Планируется: improve the documentation для 5.x после выпуска GA; Я понимаю, что документация может быть более ясной во многих местах, и любая помощь в этой области будет наиболее оценена :)
The documentation for the Percolate query создан из the integration test for it. Вытянув все части для примера, using details from you other question. Сначала давайте определим модели POCO
public class LogEntryModel
{
public string Message { get; set; }
public DateTimeOffset Timestamp { get; set; }
}
public class PercolatedQuery
{
public string Id { get; set; }
public QueryContainer Query { get; set; }
}
Мы собираемся свободно отображать все свойства вместо использования атрибутов сопоставления. Свободные сопоставления являются самыми мощными и могут выражать все способы отображения в Elasticsearch.
Теперь создайте настройки подключения и клиент для работы с Elasticsearch.
var pool = new SingleNodeConnectionPool(new Uri($"http://localhost:9200"));
var logIndex = "log_entries";
var connectionSettings = new ConnectionSettings(pool)
// infer mapping for logs
.InferMappingFor<LogEntryModel>(m => m
.IndexName(logIndex)
.TypeName("log_entry")
)
// infer mapping for percolated queries
.InferMappingFor<PercolatedQuery>(m => m
.IndexName(logIndex)
.TypeName("percolated_query")
);
var client = new ElasticClient(connectionSettings);
Мы можем указать имя индекса и имя типа для вывода для наших POCOs; то есть когда NEST делает запрос с использованием LogEntryModel
или PercolatedQuery
в качестве параметра типового типа в запросе (например, T
в .Search<T>()
), он будет использовать имя и имя предполагаемого индекса, если они не указаны в запросе.
Теперь, удалить индекс, так что мы можем начать с нуля
// delete the index if it already exists
if (client.IndexExists(logIndex).Exists)
client.DeleteIndex(logIndex);
И создать индекс
client.CreateIndex(logIndex, c => c
.Settings(s => s
.NumberOfShards(1)
.NumberOfReplicas(0)
)
.Mappings(m => m
.Map<LogEntryModel>(mm => mm
.AutoMap()
)
.Map<PercolatedQuery>(mm => mm
.AutoMap()
.Properties(p => p
// map the query field as a percolator type
.Percolator(pp => pp
.Name(n => n.Query)
)
)
)
)
);
Query
свойство на PercolatedQuery
сопоставляется как percolator
типа. Это новое в Elasticsearch 5.0. Запрос отображение выглядит
{
"settings": {
"index.number_of_replicas": 0,
"index.number_of_shards": 1
},
"mappings": {
"log_entry": {
"properties": {
"message": {
"fields": {
"keyword": {
"type": "keyword"
}
},
"type": "text"
},
"timestamp": {
"type": "date"
}
}
},
"percolated_query": {
"properties": {
"id": {
"fields": {
"keyword": {
"type": "keyword"
}
},
"type": "text"
},
"query": {
"type": "percolator"
}
}
}
}
}
Теперь мы готовы к индексу запрос
client.Index(new PercolatedQuery
{
Id = "std_query",
Query = new MatchQuery
{
Field = Infer.Field<LogEntryModel>(entry => entry.Message),
Query = "just a text"
}
}, d => d.Index(logIndex).Refresh(Refresh.WaitFor));
С запросом проиндексированого Давайте просачиваются это документ
var logEntry = new LogEntryModel
{
Timestamp = DateTimeOffset.UtcNow,
Message = "some log message text"
};
// run percolator on the logEntry instance
var searchResponse = client.Search<PercolatedQuery>(s => s
.Query(q => q
.Percolate(p => p
// field that contains the query
.Field(f => f.Query)
// details about the document to run the stored query against.
// NOTE: This does not index the document, only runs percolation
.DocumentType<LogEntryModel>()
.Document(logEntry)
)
)
);
// outputs 1
Console.WriteLine(searchResponse.Documents.Count());
В процеживают запрос с идентификатором "std_query"
возвращается в searchResponse.Documents
{
"took" : 117,
"timed_out" : false,
"_shards" : {
"total" : 1,
"successful" : 1,
"failed" : 0
},
"hits" : {
"total" : 1,
"max_score" : 0.2876821,
"hits" : [
{
"_index" : "log_entries",
"_type" : "percolated_query",
"_id" : "std_query",
"_score" : 0.2876821,
"_source" : {
"id" : "std_query",
"query" : {
"match" : {
"message" : {
"query" : "just a text"
}
}
}
}
}
]
}
}
Это пример перколяции экземпляра документа. Перколяция также может быть проведена против уже проиндексированных документов
var searchResponse = client.Search<PercolatedQuery>(s => s
.Query(q => q
.Percolate(p => p
// field that contains the query
.Field(f => f.Query)
// percolate an already indexed log entry
.DocumentType<LogEntryModel>()
.Id("log entry id")
.Index<LogEntryModel>()
.Type<LogEntryModel>()
)
)
);
Не каждый герой носит плащ.Мой босс разорвал бы голову, если бы у меня не было рабочего решения до понедельника. Ты буквально спас мне жизнь, так что спасибо :). –
Не беспокойтесь, рад, что это помогло :) –
Большое вам спасибо за этот хороший образец кода перколятора. –