API geoespacial
O Lucene Distribuído suporta a indexação dos documentos com as coordenadas geoespaciais e, posteriormente, a consulta desses documentos indexados para pesquisa baseada em localização. Para tanto, o Distributed Lucene utiliza o Spatial4n
biblioteca.
Pré-requisitos
- Para aprender sobre os pré-requisitos padrão necessários para trabalhar com todos os NCache recursos do lado do cliente, consulte a página fornecida em Pré-requisitos da API do lado do cliente.
- Certifique-se de ter criado e iniciado um cache do Lucene por meio do NCache Centro de Gerenciamento or Interface da Linha de comando.
- Certifique-se de que seu aplicativo não esteja usando nenhuma DLL/referência nativa do Lucene.
- Para detalhes da API, consulte: Documento Espacial, Estratégia Espacial, GeohashPrefixTreeName, Estratégia RecursivaPrefixTree, NCacheDiretório, IndexWriterConfig, LuceneVersão, Standard Analyzer, IndexWriter, Contexto Espacial, ReadShapeFromWkt, Pesquisador de índice, Leitor de Índice, Leitor de diretório, Classe SortField, SortFieldType, SpatialArgs, Operação Espacial, DistânciaUtils, Fazer Círculo, Dist2Graus, MakeFilter, Principais documentos, MatchAllDocsQuery, dispor.
Documento Espacial
Os documentos espaciais são criados usando o SpatialDocument
aula. Esses documentos são posteriormente usados para fins de indexação. Esta classe é específica para o Lucene Distribuído.
A SpatialDocument
consiste nas formas do IShape
aula junto com um Document
. Essas formas serão então transformadas em campos indexáveis no lado do servidor por meio de um Strategy
. Os campos indexáveis serão adicionados ao Document
via IndexWriter
.
No exemplo a seguir, um método para um documento espacial é criado com o tipo de retorno do SpatialDocument
classe, este método é então usado no próximo exemplo.
public static SpatialDocument CreateSpatialDocument(int id, SpatialStrategy strategy, params IShape[] shapes)
{
Document doc = new Document();
doc.Add(new Int32Field("id", id, Field.Store.YES));
foreach (IShape shape in shapes)
{
IPoint pt = (IPoint)shape;
doc.Add(new StoredField(strategy.FieldName,
pt.X.ToString(CultureInfo.InvariantCulture) + " " +
pt.Y.ToString(CultureInfo.InvariantCulture)));
}
return new SpatialDocument()
{
Document = doc,
Shapes = shapes
};
}
Exemplo de API espacial
A SpatialStrategy
A classe encapsula uma abordagem para indexar e pesquisar os documentos com base nas formas. O Distributed Lucene suporta todas as estratégias espaciais suportadas pelo Lucene. O funcionamento da API espacial é o mesmo em ambos, o Distributed Lucene e o Lucene, exceto pelo conceito de um SpatialDocument
classe que está presente apenas no Lucene distribuído.
No exemplo a seguir, os documentos espaciais são definidos usando o CreateSpatialDocument
método criado no exemplo anterior e, em seguida, adicionado ao IndexWriter
com o SpatialStrategy
definiram. Os documentos são posteriormente pesquisados com o IndexSearcher
, e os resultados são verificados posteriormente.
// Precondition: Lucene cache is already connected
string cache = "luceneCache";
string index = "normalIndex";
IndexReader indexReader = null;
IndexSearcher indexSearcher = null;
// Initialize prefix tree with depth level
var maxLevels = 11;
var grid = new GeohashPrefixTree(SpatialContext.GEO,
maxLevels);
// Define strategy
var strategy = new RecursivePrefixTreeStrategy(grid,
"myGeoField");
// Open NCache directory on index
var directory = NCacheDirectory.Open(cache, index);
// Configure and initalize index writer
var indexWriterConfig = new IndexWriterConfig
(LuceneVersion.LUCENE_48, new StandardAnalyzer
(LuceneVersion.LUCENE_48));
IndexWriter writer = new IndexWriter(directory,
indexWriterConfig);
// Add spatial documents to document with index writer
writer.AddDocument(CreateSpatialDocument(2, strategy,
SpatialContext.GEO.MakePoint(-80.93, 33.77)), strategy);
writer.AddDocument(CreateSpatialDocument(4, strategy,
SpatialContext.GEO.ReadShapeFromWkt("POINT(60.9289094
-50.7693246)")), strategy);
writer.AddDocument(CreateSpatialDocument(20,
strategy, SpatialContext.GEO.MakePoint(0.1, 0.1),
SpatialContext.GEO.MakePoint(0, 0)), strategy);
// Open index reader on directory
indexReader = DirectoryReader.Open(directory);
// Open index searcher on index reader
indexSearcher = new IndexSearcher(indexReader);
// Define sorting strategy
Sort idSort = new Sort(new SortField("id",
SortFieldType.INT32));
// Define spatial arguments
SpatialArgs args = new SpatialArgs(SpatialOperation.
Intersects, SpatialContext.GEO.MakeCircle(-80.0, 33.
0, DistanceUtils.Dist2Degrees(200, DistanceUtils.
EARTH_MEAN_RADIUS_KM)));
// Define the filter with spatial arguments
Filter filter = strategy.MakeFilter(args);
// Search top docs
TopDocs docs = indexSearcher.Search(new
MatchAllDocsQuery(), filter, 10, idSort);
if (indexSearcher != null) indexSearcher.Dispose();
if (indexReader != null) indexReader.Dispose();
Note
Não descartando o NCacheDirectory
, IndexReader
, IndexWriter
, IndexSearcher
e DirectoryTaxonomyReader
levará ao consumo extra de memória no lado do servidor.
Recursos adicionais
NCache também fornece um aplicativo de amostra para a API geoespacial no Distributed Lucene em GitHub
Veja também
.INTERNET: DistribuídoLucene.Net.Spatial espaço para nome.