As consultas geoespaciais dividem-se nos seguintes tipos: consulta por distância geográfica, consulta por caixa delimitadora geográfica e consulta por polígono geográfico.
Pré-requisitos
Instância OTSClient inicializada. Para mais informações, consulte Inicializar uma instância OTSClient.
Tabela de dados criada e preenchida. Para mais informações, consulte Criar tabelas de dados e Gravar dados.
Índice de pesquisa criado para a tabela de dados. Para mais informações, consulte Criar um índice de pesquisa.
Consulta por distância geográfica
A consulta por distância geográfica permite definir uma área circular como condição de filtro, composta por um ponto central e um raio. O Tablestore retorna as linhas em que o valor da coluna Geopoint está dentro dessa área circular.
-
Parâmetros
Parâmetro
Descrição
tableName
Nome da tabela de dados.
indexName
Nome do índice de pesquisa.
query
Tipo da consulta. Defina o tipo de consulta como TableStore.QueryType.GEO_DISTANCE_QUERY.
fieldName
Nome do campo. Os valores deste campo devem ser do tipo Geopoint.
centerPoint
Par de coordenadas do ponto central, composto por latitude e longitude.
O valor deve seguir o formato "latitude,longitude". Intervalos válidos: latitude [-90,90] e longitude [-180,180]. Exemplo: “35,8,-45,91".
distance
Raio da área geográfica circular. Este parâmetro aceita valores do tipo DOUBLE. Unidade: metros.
-
Exemplos
O código abaixo demonstra como consultar linhas cujo valor na coluna Col_GeoPoint esteja dentro de uma área geográfica circular específica.
client.search({ tableName: TABLE_NAME, indexName: INDEX_NAME, searchQuery: { offset: 0, limit: 10, // To query only the number of rows that meet the query conditions without specific data, set the limit parameter to 0. query: { // Set the query type to TableStore.QueryType.GEO_DISTANCE_QUERY. queryType: TableStore.QueryType.GEO_DISTANCE_QUERY, query: { fieldName: "Col_GeoPoint", centerPoint: "1.1", // Specify the coordinate pair for the central point. distance: 10000 // Set the distance from the central point to a value smaller than or equal to 10,000. Unit: meter. } }, getTotalCount: true // Specify whether to return the total number of rows that meet the query conditions. Default value: false. }, columnToGet: { // Specify the columns that you want to return. You can set the parameter to RETURN_SPECIFIED to return the specified columns, RETURN_ALL to return all columns, RETURN_ALL_FROM_INDEX to return all columns in the search index, or RETURN_NONE to return only the primary key columns. returnType: TableStore.ColumnReturnType.RETURN_ALL } }, function (err, data) { if (err) { console.log('error:', err); return; } console.log('success:', JSON.stringify(data, null, 2)); });
Consulta por caixa delimitadora geográfica
Na consulta por caixa delimitadora geográfica, você define uma área retangular como condição de filtro. O Tablestore retorna as linhas em que o valor da coluna Geopoint está contido nessa área retangular.
-
Parâmetros
Parâmetro
Descrição
tableName
Nome da tabela de dados.
indexName
Nome do índice de pesquisa.
query
Tipo da consulta. Defina o tipo de consulta como TableStore.QueryType.GEO_BOUNDING_BOX_QUERY.
fieldName
Nome do campo. Os valores deste campo devem ser do tipo Geopoint.
topLeft
Par de coordenadas do canto superior esquerdo da área geográfica retangular.
bottomRight
Par de coordenadas do canto inferior direito da área geográfica retangular. Os pontos superior esquerdo e inferior direito definem unicamente a área retangular.
O valor deve seguir o formato "latitude,longitude". Intervalos válidos: latitude [-90,90] e longitude [-180,180]. Exemplo: “35,8,-45,91".
-
Exemplos
O exemplo a seguir mostra como consultar linhas onde o valor da coluna Col_GeoPoint está dentro de uma área retangular definida pelo canto superior esquerdo com coordenadas "10,0" e canto inferior direito com coordenadas "0,10":
client.search({ tableName: TABLE_NAME, indexName: INDEX_NAME, searchQuery: { offset: 0, limit: 10, // To query only the number of rows that meet the query conditions without specific data, set the limit parameter to 0. query: { // Set the query type to TableStore.QueryType.GEO_BOUNDING_BOX_QUERY. queryType: TableStore.QueryType.GEO_BOUNDING_BOX_QUERY, query: { fieldName: "Col_GeoPoint", // Specify the name of the field. topLeft: "10.0", // Specify the coordinate pair for the upper-left corner of the rectangular geographical area. bottomRight: "0.10" // Specify coordinate pair for the lower-right corner of the rectangular geographical area. } }, getTotalCount: true // Specify whether to return the total number of rows that meet the query conditions. Default value: false. }, columnToGet: { // Specify the columns that you want to return. You can set the parameter to RETURN_SPECIFIED to return the specified columns, RETURN_ALL to return all columns, RETURN_ALL_FROM_INDEX to return all columns in the search index, or RETURN_NONE to return only the primary key columns. returnType: TableStore.ColumnReturnType.RETURN_ALL } }, function (err, data) { if (err) { console.log('error:', err); return; } console.log('success:', JSON.stringify(data, null, 2)); });
Consulta por polígono geográfico
Este tipo de consulta utiliza uma área geográfica em forma de polígono. O Tablestore retorna as linhas cujo valor na coluna Geopoint se encontra dentro dos limites desse polígono.
-
Parâmetros
Parâmetro
Descrição
tableName
Nome da tabela de dados.
indexName
Nome do índice de pesquisa.
query
Tipo da consulta. Defina o tipo de consulta como TableStore.QueryType.GEO_POLYGON_QUERY.
fieldName
Nome do campo. Os valores deste campo devem ser do tipo Geopoint.
points
Pares de coordenadas dos vértices que formam a área geográfica poligonal.
Cada par deve seguir o formato "latitude,longitude". Intervalos válidos: latitude [-90,90] e longitude [-180,180]. Exemplo: “35,8,-45,91".
-
Exemplos
O trecho de código abaixo ilustra como recuperar linhas com valores na coluna Col_GeoPoint localizados dentro de uma área poligonal:
client.search({ tableName: TABLE_NAME, indexName: INDEX_NAME, searchQuery: { offset: 0, limit: 10, // To query only the number of rows that meet the query conditions without specific data, set the limit parameter to 0. query: { // Set the query type to TableStore.QueryType.GEO_POLYGON_QUERY. queryType: TableStore.QueryType.GEO_POLYGON_QUERY, query: { fieldName: "Col_GeoPoint", points: ["0,0","5,5","5,0"] // Specify coordinate pairs for vertices of a polygon geographical area. } }, getTotalCount: true // Specify whether to return the total number of rows that meet the query conditions. Default value: false. }, columnToGet: { // Specify the columns that you want to return. You can set the parameter to RETURN_SPECIFIED to return the specified columns, RETURN_ALL to return all columns, RETURN_ALL_FROM_INDEX to return all columns in the search index, or RETURN_NONE to return only the primary key columns. returnType: TableStore.ColumnReturnType.RETURN_ALL } }, function (err, data) { if (err) { console.log('error:', err); return; } console.log('success:', JSON.stringify(data, null, 2)); });
Perguntas frequentes
Referências
-
Os índices de pesquisa suportam diversos tipos de consulta: consulta por termo, consulta por termos, consulta match all, consulta match, consulta match phrase, consulta por prefixo, consulta por intervalo, consulta por curinga, consulta booleana, consulta geoespacial, consulta aninhada, consulta vetorial e consulta exists. Escolha o tipo adequado conforme suas necessidades de negócio.
Para ordenar ou paginar as linhas resultantes, utilize o recurso de classificação e paginação. Consulte Classificação e paginação para detalhes.
Caso precise eliminar duplicatas com base em uma coluna específica, use o recurso de colapso (distinct). Assim, cada valor distinto aparece apenas uma vez nos resultados. Veja mais em Colapso (distinct).
Para analisar dados da tabela, como obter valores extremos, somatórios ou contagem total de linhas, execute operações de agregação ou instruções SQL. Saiba mais em Agregação e Consulta SQL.
Se o objetivo for obter rapidamente todas as linhas correspondentes sem necessidade de ordenação, utilize a varredura paralela chamando as operações ParallelScan e ComputeSplits. Para mais detalhes, consulte Varredura paralela.