API geoespacial
Distributed Lucene admite la indexación de documentos con coordenadas geoespaciales y, posteriormente, la consulta de estos documentos indexados para búsquedas basadas en la ubicación. Para ello, Distributed Lucene utiliza el Spatial4n
biblioteca.
Requisitos previos
- Para obtener información sobre los requisitos previos estándar necesarios para trabajar con todos NCache características del lado del cliente, consulte la página proporcionada en Requisitos previos de la API del lado del cliente.
- Asegúrese de haber creado e iniciado un caché de Lucene a través del NCache Centro de gestion or Interfaz de línea de comandos.
- Asegúrese de que su aplicación no utilice ninguna DLL/referencia nativa de Lucene.
- Para obtener detalles de la API, consulte: Documento Espacial, Estrategia espacial, GeohashPrefijoÁrbol, RecursivoPrefijoÁrbolEstrategia, NCacheDirectorio, Configuración de IndexWriter, LuceneVersión, Analizador estándar, Escritor de índices, Contexto espacial, LeerFormaDesdeWkt, Buscador de índices, Lector de índices, Lector de directorios, Clase SortField, Tipo de campo de ordenación, Argumentos espaciales, Operación espacial, DistanciaUtiles, HacerCírculo, Dist2Grados, HacerFiltro, TopDocs, MatchAllDocsQuery, tiene.
Documento espacial
Los documentos espaciales se crean utilizando el SpatialDocument
clase. Estos documentos se utilizan posteriormente con fines de indexación. Esta clase es específica de Distributed Lucene.
El SpatialDocument
consiste en las formas de los IShape
clase junto con un Document
. Estas formas luego se transformarán en campos indexables en el lado del servidor a través de un Strategy
. Los campos indexables se añadirán al Document
vía IndexWriter
.
En el siguiente ejemplo, se crea un método para un documento espacial con el tipo de retorno del SpatialDocument
clase, este método se utiliza en el siguiente ejemplo.
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
};
}
Ejemplo de API espacial
El SpatialStrategy
La clase encapsula un enfoque para indexar y buscar documentos en función de las formas. Distributed Lucene admite todas las estrategias espaciales admitidas por Lucene. El funcionamiento de la API espacial es el mismo tanto en Distributed Lucene como en Lucene, excepto por el concepto de un SpatialDocument
clase que está presente en Distributed Lucene solamente.
En el siguiente ejemplo, los documentos espaciales se definen utilizando el CreateSpatialDocument
método creado en el ejemplo anterior y luego agregado al IndexWriter
con el SpatialStrategy
definido. Los documentos se buscan posteriormente con el IndexSearcher
, y los resultados se verifican 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
No disponer del NCacheDirectory
, IndexReader
, IndexWriter
, IndexSearcher
y DirectoryTaxonomyReader
provocará un consumo adicional de memoria en el lado del servidor.
Recursos adicionales
NCache también proporciona una aplicación de muestra para la API geoespacial en Distributed Lucene en GitHub
Vea también
.NETO: DistribuidoLucene.Net.Spatial espacio de nombres