地理空间索引
对地理空间数据进行索引的选项
Redis 支持两种不同的地理空间数据模式类型
GEO
:这使用一种简单格式,其中单个地理空间点指定为数字经度-纬度对。GEOSHAPE
:这使用 Well-Known Text (WKT) 格式的子集,使用地理坐标或笛卡尔坐标指定点和多边形。
以下部分解释了如何为这些模式类型创建索引。有关这两种类型的完整说明,请参阅地理空间参考页。
GEO
以下命令为包含地理空间数据且字段名为 location
的 JSON 对象创建一个 GEO
索引
> FT.CREATE productidx ON JSON PREFIX 1 product: SCHEMA $.location AS location GEO
OK
您是否厌倦了使用 redis-cli?试试 Redis Insight - Redis 开发者 GUI。
import redis
from redis.commands.json.path import Path
from redis.commands.search.field import TextField, GeoField, GeoShapeField
from redis.commands.search.indexDefinition import IndexDefinition, IndexType
from redis.commands.search.query import Query
r = redis.Redis()
geo_schema = (
GeoField("$.location", as_name="location")
)
geo_index_create_result = r.ft("productidx").create_index(
geo_schema,
definition=IndexDefinition(
prefix=["product:"], index_type=IndexType.JSON
)
)
print(geo_index_create_result) # >>> True
prd46885 = {
"description": "Navy Blue Slippers",
"price": 45.99,
"city": "Denver",
"location": "-104.991531, 39.742043"
}
json_add_result_1 = r.json().set("product:46885", Path.root_path(), prd46885)
print(json_add_result_1) # >>> True
prd46886 = {
"description": "Bright Green Socks",
"price": 25.50,
"city": "Fort Collins",
"location": "-105.0618814,40.5150098"
}
json_add_result_2 = r.json().set("product:46886", Path.root_path(), prd46886)
print(json_add_result_2) # >>> True
geo_result = r.ft("productidx").search(
"@location:[-104.800644 38.846127 100 mi]"
)
print(geo_result)
# >>> Result{1 total, docs: [Document {'id': 'product:46885'...
geom_schema = (
TextField("$.name", as_name="name"),
GeoShapeField(
"$.geom", as_name="geom", coord_system=GeoShapeField.FLAT
)
)
geom_index_create_result = r.ft("geomidx").create_index(
geom_schema,
definition=IndexDefinition(
prefix=["shape:"], index_type=IndexType.JSON
)
)
print(geom_index_create_result) # True
shape1 = {
"name": "Green Square",
"geom": "POLYGON ((1 1, 1 3, 3 3, 3 1, 1 1))"
}
gm_json_res_1 = r.json().set("shape:1", Path.root_path(), shape1)
print(gm_json_res_1) # >>> True
shape2 = {
"name": "Red Rectangle",
"geom": "POLYGON ((2 2.5, 2 3.5, 3.5 3.5, 3.5 2.5, 2 2.5))"
}
gm_json_res_2 = r.json().set("shape:2", Path.root_path(), shape2)
print(gm_json_res_2) # >>> True
shape3 = {
"name": "Blue Triangle",
"geom": "POLYGON ((3.5 1, 3.75 2, 4 1, 3.5 1))"
}
gm_json_res_3 = r.json().set("shape:3", Path.root_path(), shape3)
print(gm_json_res_3) # >>> True
shape4 = {
"name": "Purple Point",
"geom": "POINT (2 2)"
}
gm_json_res_4 = r.json().set("shape:4", Path.root_path(), shape4)
print(gm_json_res_4) # >>> True
geom_result = r.ft("geomidx").search(
Query(
"(-@name:(Green Square) @geom:[WITHIN $qshape])"
).dialect(4).paging(0, 1),
query_params={
"qshape": "POLYGON ((1 1, 1 3, 3 3, 3 1, 1 1))"
}
)
print(geom_result)
# >>> Result{1 total, docs: [Document {'id': 'shape:4'...
import org.json.JSONObject;
import redis.clients.jedis.UnifiedJedis;
import redis.clients.jedis.json.Path2;
import redis.clients.jedis.search.Document;
import redis.clients.jedis.search.FTCreateParams;
import redis.clients.jedis.search.FTSearchParams;
import redis.clients.jedis.search.IndexDataType;
import redis.clients.jedis.search.schemafields.*;
import redis.clients.jedis.search.schemafields.GeoShapeField.CoordinateSystem;
import redis.clients.jedis.search.SearchResult;
import redis.clients.jedis.exceptions.JedisDataException;
import static org.junit.jupiter.api.Assertions.assertEquals;
public class GeoIndexExample {
public void run() {
UnifiedJedis jedis = new UnifiedJedis("redis://localhost:6379");
SchemaField[] geoSchema = {
GeoField.of("$.location").as("location")
};
String geoIdxCreateResult = jedis.ftCreate("productidx",
FTCreateParams.createParams()
.on(IndexDataType.JSON)
.addPrefix("product:"),
geoSchema
);
JSONObject prd46885 = new JSONObject()
.put("description", "Navy Blue Slippers")
.put("price", 45.99)
.put("city", "Denver")
.put("location", "-104.991531, 39.742043");
String jsonAddResult1 = jedis.jsonSet("product:46885", new Path2("$"), prd46885);
System.out.println(jsonAddResult1); // >>> OK
JSONObject prd46886 = new JSONObject()
.put("description", "Bright Green Socks")
.put("price", 25.50)
.put("city", "Fort Collins")
.put("location", "-105.0618814,40.5150098");
String jsonAddResult2 = jedis.jsonSet("product:46886", new Path2("$"), prd46886);
System.out.println(jsonAddResult2); // >>> OK
SearchResult geoResult = jedis.ftSearch("productidx",
"@location:[-104.800644 38.846127 100 mi]"
);
System.out.println(geoResult.getTotalResults()); // >>> 1
for (Document doc: geoResult.getDocuments()) {
System.out.println(doc.getId());
}
// >>> product:46885
SchemaField[] geomSchema = {
TextField.of("$.name").as("name"),
GeoShapeField.of("$.geom", CoordinateSystem.FLAT).as("geom")
};
String geomIndexCreateResult = jedis.ftCreate("geomidx",
FTCreateParams.createParams()
.on(IndexDataType.JSON)
.addPrefix("shape"),
geomSchema
);
System.out.println(geomIndexCreateResult); // >>> OK
JSONObject shape1 = new JSONObject()
.put("name", "Green Square")
.put("geom", "POLYGON ((1 1, 1 3, 3 3, 3 1, 1 1))");
String gmJsonRes1 = jedis.jsonSet("shape:1", new Path2("$"), shape1);
System.out.println(gmJsonRes1); // >>> OK
JSONObject shape2 = new JSONObject()
.put("name", "Red Rectangle")
.put("geom", "POLYGON ((2 2.5, 2 3.5, 3.5 3.5, 3.5 2.5, 2 2.5))");
String gmJsonRes2 = jedis.jsonSet("shape:2", new Path2("$"), shape2);
System.out.println(gmJsonRes2); // >>> OK
JSONObject shape3 = new JSONObject()
.put("name", "Blue Triangle")
.put("geom", "POLYGON ((3.5 1, 3.75 2, 4 1, 3.5 1))");
String gmJsonRes3 = jedis.jsonSet("shape:3", new Path2("$"), shape3);
System.out.println(gmJsonRes3); // >>> OK
JSONObject shape4 = new JSONObject()
.put("name", "Purple Point")
.put("geom", "POINT (2 2)");
String gmJsonRes4 = jedis.jsonSet("shape:4", new Path2("$"), shape4);
System.out.println(gmJsonRes4); // >>> OK
SearchResult geomResult = jedis.ftSearch("geomidx",
"(-@name:(Green Square) @geom:[WITHIN $qshape])",
FTSearchParams.searchParams()
.addParam("qshape", "POLYGON ((1 1, 1 3, 3 3, 3 1, 1 1))")
.dialect(4)
.limit(0, 1)
);
System.out.println(geomResult.getTotalResults()); // >>> 1
for (Document doc: geomResult.getDocuments()) {
System.out.println(doc.getId());
}
// shape:4
jedis.close();
}
}
package example_commands_test
import (
"context"
"fmt"
"github.com/redis/go-redis/v9"
)
func ExampleClient_geoindex() {
ctx := context.Background()
rdb := redis.NewClient(&redis.Options{
Addr: "localhost:6379",
Password: "", // no password docs
DB: 0, // use default DB
Protocol: 2,
})
geoCreateResult, err := rdb.FTCreate(ctx,
"productidx",
&redis.FTCreateOptions{
OnJSON: true,
Prefix: []interface{}{"product:"},
},
&redis.FieldSchema{
FieldName: "$.location",
As: "location",
FieldType: redis.SearchFieldTypeGeo,
},
).Result()
if err != nil {
panic(err)
}
fmt.Println(geoCreateResult) // >>> OK
prd46885 := map[string]interface{}{
"description": "Navy Blue Slippers",
"price": 45.99,
"city": "Denver",
"location": "-104.991531, 39.742043",
}
gjResult1, err := rdb.JSONSet(ctx, "product:46885", "$", prd46885).Result()
if err != nil {
panic(err)
}
fmt.Println(gjResult1) // >>> OK
prd46886 := map[string]interface{}{
"description": "Bright Green Socks",
"price": 25.50,
"city": "Fort Collins",
"location": "-105.0618814,40.5150098",
}
gjResult2, err := rdb.JSONSet(ctx, "product:46886", "$", prd46886).Result()
if err != nil {
panic(err)
}
fmt.Println(gjResult2) // >>> OK
geoQueryResult, err := rdb.FTSearch(ctx, "productidx",
"@location:[-104.800644 38.846127 100 mi]",
).Result()
if err != nil {
panic(err)
}
fmt.Println(geoQueryResult)
// >>> {1 [{product:46885...
geomCreateResult, err := rdb.FTCreate(ctx, "geomidx",
&redis.FTCreateOptions{
OnJSON: true,
Prefix: []interface{}{"shape:"},
},
&redis.FieldSchema{
FieldName: "$.name",
As: "name",
FieldType: redis.SearchFieldTypeText,
},
&redis.FieldSchema{
FieldName: "$.geom",
As: "geom",
FieldType: redis.SearchFieldTypeGeoShape,
GeoShapeFieldType: "FLAT",
},
).Result()
if err != nil {
panic(err)
}
fmt.Println(geomCreateResult) // >>> OK
shape1 := map[string]interface{}{
"name": "Green Square",
"geom": "POLYGON ((1 1, 1 3, 3 3, 3 1, 1 1))",
}
gmjResult1, err := rdb.JSONSet(ctx, "shape:1", "$", shape1).Result()
if err != nil {
panic(err)
}
fmt.Println(gmjResult1) // >>> OK
shape2 := map[string]interface{}{
"name": "Red Rectangle",
"geom": "POLYGON ((2 2.5, 2 3.5, 3.5 3.5, 3.5 2.5, 2 2.5))",
}
gmjResult2, err := rdb.JSONSet(ctx, "shape:2", "$", shape2).Result()
if err != nil {
panic(err)
}
fmt.Println(gmjResult2) // >>> OK
shape3 := map[string]interface{}{
"name": "Blue Triangle",
"geom": "POLYGON ((3.5 1, 3.75 2, 4 1, 3.5 1))",
}
gmjResult3, err := rdb.JSONSet(ctx, "shape:3", "$", shape3).Result()
if err != nil {
panic(err)
}
fmt.Println(gmjResult3) // >>> OK
shape4 := map[string]interface{}{
"name": "Purple Point",
"geom": "POINT (2 2)",
}
gmjResult4, err := rdb.JSONSet(ctx, "shape:4", "$", shape4).Result()
if err != nil {
panic(err)
}
fmt.Println(gmjResult4) // >>> OK
geomQueryResult, err := rdb.FTSearchWithArgs(ctx, "geomidx",
"(-@name:(Green Square) @geom:[WITHIN $qshape])",
&redis.FTSearchOptions{
Params: map[string]interface{}{
"qshape": "POLYGON ((1 1, 1 3, 3 3, 3 1, 1 1))",
},
DialectVersion: 4,
Limit: 1,
},
).Result()
if err != nil {
panic(err)
}
fmt.Println(geomQueryResult)
// >>> {1 [{shape:4...
}
如果您现在添加带有 product:
前缀和 location
字段的 JSON 对象,它们将自动添加到索引中
> JSON.SET product:46885 $ '{"description": "Navy Blue Slippers","price": 45.99,"city": "Denver","location": "-104.991531, 39.742043"}'
OK
> JSON.SET product:46886 $ '{"description": "Bright Green Socks","price": 25.50,"city": "Fort Collins","location": "-105.0618814,40.5150098"}'
OK
您是否厌倦了使用 redis-cli?试试 Redis Insight - Redis 开发者 GUI。
import redis
from redis.commands.json.path import Path
from redis.commands.search.field import TextField, GeoField, GeoShapeField
from redis.commands.search.indexDefinition import IndexDefinition, IndexType
from redis.commands.search.query import Query
r = redis.Redis()
geo_schema = (
GeoField("$.location", as_name="location")
)
geo_index_create_result = r.ft("productidx").create_index(
geo_schema,
definition=IndexDefinition(
prefix=["product:"], index_type=IndexType.JSON
)
)
print(geo_index_create_result) # >>> True
prd46885 = {
"description": "Navy Blue Slippers",
"price": 45.99,
"city": "Denver",
"location": "-104.991531, 39.742043"
}
json_add_result_1 = r.json().set("product:46885", Path.root_path(), prd46885)
print(json_add_result_1) # >>> True
prd46886 = {
"description": "Bright Green Socks",
"price": 25.50,
"city": "Fort Collins",
"location": "-105.0618814,40.5150098"
}
json_add_result_2 = r.json().set("product:46886", Path.root_path(), prd46886)
print(json_add_result_2) # >>> True
geo_result = r.ft("productidx").search(
"@location:[-104.800644 38.846127 100 mi]"
)
print(geo_result)
# >>> Result{1 total, docs: [Document {'id': 'product:46885'...
geom_schema = (
TextField("$.name", as_name="name"),
GeoShapeField(
"$.geom", as_name="geom", coord_system=GeoShapeField.FLAT
)
)
geom_index_create_result = r.ft("geomidx").create_index(
geom_schema,
definition=IndexDefinition(
prefix=["shape:"], index_type=IndexType.JSON
)
)
print(geom_index_create_result) # True
shape1 = {
"name": "Green Square",
"geom": "POLYGON ((1 1, 1 3, 3 3, 3 1, 1 1))"
}
gm_json_res_1 = r.json().set("shape:1", Path.root_path(), shape1)
print(gm_json_res_1) # >>> True
shape2 = {
"name": "Red Rectangle",
"geom": "POLYGON ((2 2.5, 2 3.5, 3.5 3.5, 3.5 2.5, 2 2.5))"
}
gm_json_res_2 = r.json().set("shape:2", Path.root_path(), shape2)
print(gm_json_res_2) # >>> True
shape3 = {
"name": "Blue Triangle",
"geom": "POLYGON ((3.5 1, 3.75 2, 4 1, 3.5 1))"
}
gm_json_res_3 = r.json().set("shape:3", Path.root_path(), shape3)
print(gm_json_res_3) # >>> True
shape4 = {
"name": "Purple Point",
"geom": "POINT (2 2)"
}
gm_json_res_4 = r.json().set("shape:4", Path.root_path(), shape4)
print(gm_json_res_4) # >>> True
geom_result = r.ft("geomidx").search(
Query(
"(-@name:(Green Square) @geom:[WITHIN $qshape])"
).dialect(4).paging(0, 1),
query_params={
"qshape": "POLYGON ((1 1, 1 3, 3 3, 3 1, 1 1))"
}
)
print(geom_result)
# >>> Result{1 total, docs: [Document {'id': 'shape:4'...
import org.json.JSONObject;
import redis.clients.jedis.UnifiedJedis;
import redis.clients.jedis.json.Path2;
import redis.clients.jedis.search.Document;
import redis.clients.jedis.search.FTCreateParams;
import redis.clients.jedis.search.FTSearchParams;
import redis.clients.jedis.search.IndexDataType;
import redis.clients.jedis.search.schemafields.*;
import redis.clients.jedis.search.schemafields.GeoShapeField.CoordinateSystem;
import redis.clients.jedis.search.SearchResult;
import redis.clients.jedis.exceptions.JedisDataException;
import static org.junit.jupiter.api.Assertions.assertEquals;
public class GeoIndexExample {
public void run() {
UnifiedJedis jedis = new UnifiedJedis("redis://localhost:6379");
SchemaField[] geoSchema = {
GeoField.of("$.location").as("location")
};
String geoIdxCreateResult = jedis.ftCreate("productidx",
FTCreateParams.createParams()
.on(IndexDataType.JSON)
.addPrefix("product:"),
geoSchema
);
JSONObject prd46885 = new JSONObject()
.put("description", "Navy Blue Slippers")
.put("price", 45.99)
.put("city", "Denver")
.put("location", "-104.991531, 39.742043");
String jsonAddResult1 = jedis.jsonSet("product:46885", new Path2("$"), prd46885);
System.out.println(jsonAddResult1); // >>> OK
JSONObject prd46886 = new JSONObject()
.put("description", "Bright Green Socks")
.put("price", 25.50)
.put("city", "Fort Collins")
.put("location", "-105.0618814,40.5150098");
String jsonAddResult2 = jedis.jsonSet("product:46886", new Path2("$"), prd46886);
System.out.println(jsonAddResult2); // >>> OK
SearchResult geoResult = jedis.ftSearch("productidx",
"@location:[-104.800644 38.846127 100 mi]"
);
System.out.println(geoResult.getTotalResults()); // >>> 1
for (Document doc: geoResult.getDocuments()) {
System.out.println(doc.getId());
}
// >>> product:46885
SchemaField[] geomSchema = {
TextField.of("$.name").as("name"),
GeoShapeField.of("$.geom", CoordinateSystem.FLAT).as("geom")
};
String geomIndexCreateResult = jedis.ftCreate("geomidx",
FTCreateParams.createParams()
.on(IndexDataType.JSON)
.addPrefix("shape"),
geomSchema
);
System.out.println(geomIndexCreateResult); // >>> OK
JSONObject shape1 = new JSONObject()
.put("name", "Green Square")
.put("geom", "POLYGON ((1 1, 1 3, 3 3, 3 1, 1 1))");
String gmJsonRes1 = jedis.jsonSet("shape:1", new Path2("$"), shape1);
System.out.println(gmJsonRes1); // >>> OK
JSONObject shape2 = new JSONObject()
.put("name", "Red Rectangle")
.put("geom", "POLYGON ((2 2.5, 2 3.5, 3.5 3.5, 3.5 2.5, 2 2.5))");
String gmJsonRes2 = jedis.jsonSet("shape:2", new Path2("$"), shape2);
System.out.println(gmJsonRes2); // >>> OK
JSONObject shape3 = new JSONObject()
.put("name", "Blue Triangle")
.put("geom", "POLYGON ((3.5 1, 3.75 2, 4 1, 3.5 1))");
String gmJsonRes3 = jedis.jsonSet("shape:3", new Path2("$"), shape3);
System.out.println(gmJsonRes3); // >>> OK
JSONObject shape4 = new JSONObject()
.put("name", "Purple Point")
.put("geom", "POINT (2 2)");
String gmJsonRes4 = jedis.jsonSet("shape:4", new Path2("$"), shape4);
System.out.println(gmJsonRes4); // >>> OK
SearchResult geomResult = jedis.ftSearch("geomidx",
"(-@name:(Green Square) @geom:[WITHIN $qshape])",
FTSearchParams.searchParams()
.addParam("qshape", "POLYGON ((1 1, 1 3, 3 3, 3 1, 1 1))")
.dialect(4)
.limit(0, 1)
);
System.out.println(geomResult.getTotalResults()); // >>> 1
for (Document doc: geomResult.getDocuments()) {
System.out.println(doc.getId());
}
// shape:4
jedis.close();
}
}
package example_commands_test
import (
"context"
"fmt"
"github.com/redis/go-redis/v9"
)
func ExampleClient_geoindex() {
ctx := context.Background()
rdb := redis.NewClient(&redis.Options{
Addr: "localhost:6379",
Password: "", // no password docs
DB: 0, // use default DB
Protocol: 2,
})
geoCreateResult, err := rdb.FTCreate(ctx,
"productidx",
&redis.FTCreateOptions{
OnJSON: true,
Prefix: []interface{}{"product:"},
},
&redis.FieldSchema{
FieldName: "$.location",
As: "location",
FieldType: redis.SearchFieldTypeGeo,
},
).Result()
if err != nil {
panic(err)
}
fmt.Println(geoCreateResult) // >>> OK
prd46885 := map[string]interface{}{
"description": "Navy Blue Slippers",
"price": 45.99,
"city": "Denver",
"location": "-104.991531, 39.742043",
}
gjResult1, err := rdb.JSONSet(ctx, "product:46885", "$", prd46885).Result()
if err != nil {
panic(err)
}
fmt.Println(gjResult1) // >>> OK
prd46886 := map[string]interface{}{
"description": "Bright Green Socks",
"price": 25.50,
"city": "Fort Collins",
"location": "-105.0618814,40.5150098",
}
gjResult2, err := rdb.JSONSet(ctx, "product:46886", "$", prd46886).Result()
if err != nil {
panic(err)
}
fmt.Println(gjResult2) // >>> OK
geoQueryResult, err := rdb.FTSearch(ctx, "productidx",
"@location:[-104.800644 38.846127 100 mi]",
).Result()
if err != nil {
panic(err)
}
fmt.Println(geoQueryResult)
// >>> {1 [{product:46885...
geomCreateResult, err := rdb.FTCreate(ctx, "geomidx",
&redis.FTCreateOptions{
OnJSON: true,
Prefix: []interface{}{"shape:"},
},
&redis.FieldSchema{
FieldName: "$.name",
As: "name",
FieldType: redis.SearchFieldTypeText,
},
&redis.FieldSchema{
FieldName: "$.geom",
As: "geom",
FieldType: redis.SearchFieldTypeGeoShape,
GeoShapeFieldType: "FLAT",
},
).Result()
if err != nil {
panic(err)
}
fmt.Println(geomCreateResult) // >>> OK
shape1 := map[string]interface{}{
"name": "Green Square",
"geom": "POLYGON ((1 1, 1 3, 3 3, 3 1, 1 1))",
}
gmjResult1, err := rdb.JSONSet(ctx, "shape:1", "$", shape1).Result()
if err != nil {
panic(err)
}
fmt.Println(gmjResult1) // >>> OK
shape2 := map[string]interface{}{
"name": "Red Rectangle",
"geom": "POLYGON ((2 2.5, 2 3.5, 3.5 3.5, 3.5 2.5, 2 2.5))",
}
gmjResult2, err := rdb.JSONSet(ctx, "shape:2", "$", shape2).Result()
if err != nil {
panic(err)
}
fmt.Println(gmjResult2) // >>> OK
shape3 := map[string]interface{}{
"name": "Blue Triangle",
"geom": "POLYGON ((3.5 1, 3.75 2, 4 1, 3.5 1))",
}
gmjResult3, err := rdb.JSONSet(ctx, "shape:3", "$", shape3).Result()
if err != nil {
panic(err)
}
fmt.Println(gmjResult3) // >>> OK
shape4 := map[string]interface{}{
"name": "Purple Point",
"geom": "POINT (2 2)",
}
gmjResult4, err := rdb.JSONSet(ctx, "shape:4", "$", shape4).Result()
if err != nil {
panic(err)
}
fmt.Println(gmjResult4) // >>> OK
geomQueryResult, err := rdb.FTSearchWithArgs(ctx, "geomidx",
"(-@name:(Green Square) @geom:[WITHIN $qshape])",
&redis.FTSearchOptions{
Params: map[string]interface{}{
"qshape": "POLYGON ((1 1, 1 3, 3 3, 3 1, 1 1))",
},
DialectVersion: 4,
Limit: 1,
},
).Result()
if err != nil {
panic(err)
}
fmt.Println(geomQueryResult)
// >>> {1 [{shape:4...
}
以下查询查找位于 Colorado Springs(经度=-104.800644,纬度=38.846127)100 英里半径范围内的产品。这仅返回丹佛的位置,但 200 英里的半径也会包括柯林斯堡的位置
> FT.SEARCH productidx '@location:[-104.800644 38.846127 100 mi]'
1) "1"
2) "product:46885"
3) 1) "$"
2) "{\"description\":\"Navy Blue Slippers\",\"price\":45.99,\"city\":\"Denver\",\"location\":\"-104.991531, 39.742043\"}"
您是否厌倦了使用 redis-cli?试试 Redis Insight - Redis 开发者 GUI。
import redis
from redis.commands.json.path import Path
from redis.commands.search.field import TextField, GeoField, GeoShapeField
from redis.commands.search.indexDefinition import IndexDefinition, IndexType
from redis.commands.search.query import Query
r = redis.Redis()
geo_schema = (
GeoField("$.location", as_name="location")
)
geo_index_create_result = r.ft("productidx").create_index(
geo_schema,
definition=IndexDefinition(
prefix=["product:"], index_type=IndexType.JSON
)
)
print(geo_index_create_result) # >>> True
prd46885 = {
"description": "Navy Blue Slippers",
"price": 45.99,
"city": "Denver",
"location": "-104.991531, 39.742043"
}
json_add_result_1 = r.json().set("product:46885", Path.root_path(), prd46885)
print(json_add_result_1) # >>> True
prd46886 = {
"description": "Bright Green Socks",
"price": 25.50,
"city": "Fort Collins",
"location": "-105.0618814,40.5150098"
}
json_add_result_2 = r.json().set("product:46886", Path.root_path(), prd46886)
print(json_add_result_2) # >>> True
geo_result = r.ft("productidx").search(
"@location:[-104.800644 38.846127 100 mi]"
)
print(geo_result)
# >>> Result{1 total, docs: [Document {'id': 'product:46885'...
geom_schema = (
TextField("$.name", as_name="name"),
GeoShapeField(
"$.geom", as_name="geom", coord_system=GeoShapeField.FLAT
)
)
geom_index_create_result = r.ft("geomidx").create_index(
geom_schema,
definition=IndexDefinition(
prefix=["shape:"], index_type=IndexType.JSON
)
)
print(geom_index_create_result) # True
shape1 = {
"name": "Green Square",
"geom": "POLYGON ((1 1, 1 3, 3 3, 3 1, 1 1))"
}
gm_json_res_1 = r.json().set("shape:1", Path.root_path(), shape1)
print(gm_json_res_1) # >>> True
shape2 = {
"name": "Red Rectangle",
"geom": "POLYGON ((2 2.5, 2 3.5, 3.5 3.5, 3.5 2.5, 2 2.5))"
}
gm_json_res_2 = r.json().set("shape:2", Path.root_path(), shape2)
print(gm_json_res_2) # >>> True
shape3 = {
"name": "Blue Triangle",
"geom": "POLYGON ((3.5 1, 3.75 2, 4 1, 3.5 1))"
}
gm_json_res_3 = r.json().set("shape:3", Path.root_path(), shape3)
print(gm_json_res_3) # >>> True
shape4 = {
"name": "Purple Point",
"geom": "POINT (2 2)"
}
gm_json_res_4 = r.json().set("shape:4", Path.root_path(), shape4)
print(gm_json_res_4) # >>> True
geom_result = r.ft("geomidx").search(
Query(
"(-@name:(Green Square) @geom:[WITHIN $qshape])"
).dialect(4).paging(0, 1),
query_params={
"qshape": "POLYGON ((1 1, 1 3, 3 3, 3 1, 1 1))"
}
)
print(geom_result)
# >>> Result{1 total, docs: [Document {'id': 'shape:4'...
import org.json.JSONObject;
import redis.clients.jedis.UnifiedJedis;
import redis.clients.jedis.json.Path2;
import redis.clients.jedis.search.Document;
import redis.clients.jedis.search.FTCreateParams;
import redis.clients.jedis.search.FTSearchParams;
import redis.clients.jedis.search.IndexDataType;
import redis.clients.jedis.search.schemafields.*;
import redis.clients.jedis.search.schemafields.GeoShapeField.CoordinateSystem;
import redis.clients.jedis.search.SearchResult;
import redis.clients.jedis.exceptions.JedisDataException;
import static org.junit.jupiter.api.Assertions.assertEquals;
public class GeoIndexExample {
public void run() {
UnifiedJedis jedis = new UnifiedJedis("redis://localhost:6379");
SchemaField[] geoSchema = {
GeoField.of("$.location").as("location")
};
String geoIdxCreateResult = jedis.ftCreate("productidx",
FTCreateParams.createParams()
.on(IndexDataType.JSON)
.addPrefix("product:"),
geoSchema
);
JSONObject prd46885 = new JSONObject()
.put("description", "Navy Blue Slippers")
.put("price", 45.99)
.put("city", "Denver")
.put("location", "-104.991531, 39.742043");
String jsonAddResult1 = jedis.jsonSet("product:46885", new Path2("$"), prd46885);
System.out.println(jsonAddResult1); // >>> OK
JSONObject prd46886 = new JSONObject()
.put("description", "Bright Green Socks")
.put("price", 25.50)
.put("city", "Fort Collins")
.put("location", "-105.0618814,40.5150098");
String jsonAddResult2 = jedis.jsonSet("product:46886", new Path2("$"), prd46886);
System.out.println(jsonAddResult2); // >>> OK
SearchResult geoResult = jedis.ftSearch("productidx",
"@location:[-104.800644 38.846127 100 mi]"
);
System.out.println(geoResult.getTotalResults()); // >>> 1
for (Document doc: geoResult.getDocuments()) {
System.out.println(doc.getId());
}
// >>> product:46885
SchemaField[] geomSchema = {
TextField.of("$.name").as("name"),
GeoShapeField.of("$.geom", CoordinateSystem.FLAT).as("geom")
};
String geomIndexCreateResult = jedis.ftCreate("geomidx",
FTCreateParams.createParams()
.on(IndexDataType.JSON)
.addPrefix("shape"),
geomSchema
);
System.out.println(geomIndexCreateResult); // >>> OK
JSONObject shape1 = new JSONObject()
.put("name", "Green Square")
.put("geom", "POLYGON ((1 1, 1 3, 3 3, 3 1, 1 1))");
String gmJsonRes1 = jedis.jsonSet("shape:1", new Path2("$"), shape1);
System.out.println(gmJsonRes1); // >>> OK
JSONObject shape2 = new JSONObject()
.put("name", "Red Rectangle")
.put("geom", "POLYGON ((2 2.5, 2 3.5, 3.5 3.5, 3.5 2.5, 2 2.5))");
String gmJsonRes2 = jedis.jsonSet("shape:2", new Path2("$"), shape2);
System.out.println(gmJsonRes2); // >>> OK
JSONObject shape3 = new JSONObject()
.put("name", "Blue Triangle")
.put("geom", "POLYGON ((3.5 1, 3.75 2, 4 1, 3.5 1))");
String gmJsonRes3 = jedis.jsonSet("shape:3", new Path2("$"), shape3);
System.out.println(gmJsonRes3); // >>> OK
JSONObject shape4 = new JSONObject()
.put("name", "Purple Point")
.put("geom", "POINT (2 2)");
String gmJsonRes4 = jedis.jsonSet("shape:4", new Path2("$"), shape4);
System.out.println(gmJsonRes4); // >>> OK
SearchResult geomResult = jedis.ftSearch("geomidx",
"(-@name:(Green Square) @geom:[WITHIN $qshape])",
FTSearchParams.searchParams()
.addParam("qshape", "POLYGON ((1 1, 1 3, 3 3, 3 1, 1 1))")
.dialect(4)
.limit(0, 1)
);
System.out.println(geomResult.getTotalResults()); // >>> 1
for (Document doc: geomResult.getDocuments()) {
System.out.println(doc.getId());
}
// shape:4
jedis.close();
}
}
package example_commands_test
import (
"context"
"fmt"
"github.com/redis/go-redis/v9"
)
func ExampleClient_geoindex() {
ctx := context.Background()
rdb := redis.NewClient(&redis.Options{
Addr: "localhost:6379",
Password: "", // no password docs
DB: 0, // use default DB
Protocol: 2,
})
geoCreateResult, err := rdb.FTCreate(ctx,
"productidx",
&redis.FTCreateOptions{
OnJSON: true,
Prefix: []interface{}{"product:"},
},
&redis.FieldSchema{
FieldName: "$.location",
As: "location",
FieldType: redis.SearchFieldTypeGeo,
},
).Result()
if err != nil {
panic(err)
}
fmt.Println(geoCreateResult) // >>> OK
prd46885 := map[string]interface{}{
"description": "Navy Blue Slippers",
"price": 45.99,
"city": "Denver",
"location": "-104.991531, 39.742043",
}
gjResult1, err := rdb.JSONSet(ctx, "product:46885", "$", prd46885).Result()
if err != nil {
panic(err)
}
fmt.Println(gjResult1) // >>> OK
prd46886 := map[string]interface{}{
"description": "Bright Green Socks",
"price": 25.50,
"city": "Fort Collins",
"location": "-105.0618814,40.5150098",
}
gjResult2, err := rdb.JSONSet(ctx, "product:46886", "$", prd46886).Result()
if err != nil {
panic(err)
}
fmt.Println(gjResult2) // >>> OK
geoQueryResult, err := rdb.FTSearch(ctx, "productidx",
"@location:[-104.800644 38.846127 100 mi]",
).Result()
if err != nil {
panic(err)
}
fmt.Println(geoQueryResult)
// >>> {1 [{product:46885...
geomCreateResult, err := rdb.FTCreate(ctx, "geomidx",
&redis.FTCreateOptions{
OnJSON: true,
Prefix: []interface{}{"shape:"},
},
&redis.FieldSchema{
FieldName: "$.name",
As: "name",
FieldType: redis.SearchFieldTypeText,
},
&redis.FieldSchema{
FieldName: "$.geom",
As: "geom",
FieldType: redis.SearchFieldTypeGeoShape,
GeoShapeFieldType: "FLAT",
},
).Result()
if err != nil {
panic(err)
}
fmt.Println(geomCreateResult) // >>> OK
shape1 := map[string]interface{}{
"name": "Green Square",
"geom": "POLYGON ((1 1, 1 3, 3 3, 3 1, 1 1))",
}
gmjResult1, err := rdb.JSONSet(ctx, "shape:1", "$", shape1).Result()
if err != nil {
panic(err)
}
fmt.Println(gmjResult1) // >>> OK
shape2 := map[string]interface{}{
"name": "Red Rectangle",
"geom": "POLYGON ((2 2.5, 2 3.5, 3.5 3.5, 3.5 2.5, 2 2.5))",
}
gmjResult2, err := rdb.JSONSet(ctx, "shape:2", "$", shape2).Result()
if err != nil {
panic(err)
}
fmt.Println(gmjResult2) // >>> OK
shape3 := map[string]interface{}{
"name": "Blue Triangle",
"geom": "POLYGON ((3.5 1, 3.75 2, 4 1, 3.5 1))",
}
gmjResult3, err := rdb.JSONSet(ctx, "shape:3", "$", shape3).Result()
if err != nil {
panic(err)
}
fmt.Println(gmjResult3) // >>> OK
shape4 := map[string]interface{}{
"name": "Purple Point",
"geom": "POINT (2 2)",
}
gmjResult4, err := rdb.JSONSet(ctx, "shape:4", "$", shape4).Result()
if err != nil {
panic(err)
}
fmt.Println(gmjResult4) // >>> OK
geomQueryResult, err := rdb.FTSearchWithArgs(ctx, "geomidx",
"(-@name:(Green Square) @geom:[WITHIN $qshape])",
&redis.FTSearchOptions{
Params: map[string]interface{}{
"qshape": "POLYGON ((1 1, 1 3, 3 3, 3 1, 1 1))",
},
DialectVersion: 4,
Limit: 1,
},
).Result()
if err != nil {
panic(err)
}
fmt.Println(geomQueryResult)
// >>> {1 [{shape:4...
}
有关可用选项的更多信息,请参阅地理空间查询。
GEOSHAPE
以下命令为包含地理空间数据且字段名为 geom
的 JSON 对象创建索引。字段定义末尾的 FLAT
选项指定使用笛卡尔坐标而不是默认的球面地理坐标。使用 SPHERICAL
代替 FLAT
来明确选择坐标空间。
> FT.CREATE geomidx ON JSON PREFIX 1 shape: SCHEMA $.name AS name TEXT $.geom AS geom GEOSHAPE FLAT
OK
您是否厌倦了使用 redis-cli?试试 Redis Insight - Redis 开发者 GUI。
import redis
from redis.commands.json.path import Path
from redis.commands.search.field import TextField, GeoField, GeoShapeField
from redis.commands.search.indexDefinition import IndexDefinition, IndexType
from redis.commands.search.query import Query
r = redis.Redis()
geo_schema = (
GeoField("$.location", as_name="location")
)
geo_index_create_result = r.ft("productidx").create_index(
geo_schema,
definition=IndexDefinition(
prefix=["product:"], index_type=IndexType.JSON
)
)
print(geo_index_create_result) # >>> True
prd46885 = {
"description": "Navy Blue Slippers",
"price": 45.99,
"city": "Denver",
"location": "-104.991531, 39.742043"
}
json_add_result_1 = r.json().set("product:46885", Path.root_path(), prd46885)
print(json_add_result_1) # >>> True
prd46886 = {
"description": "Bright Green Socks",
"price": 25.50,
"city": "Fort Collins",
"location": "-105.0618814,40.5150098"
}
json_add_result_2 = r.json().set("product:46886", Path.root_path(), prd46886)
print(json_add_result_2) # >>> True
geo_result = r.ft("productidx").search(
"@location:[-104.800644 38.846127 100 mi]"
)
print(geo_result)
# >>> Result{1 total, docs: [Document {'id': 'product:46885'...
geom_schema = (
TextField("$.name", as_name="name"),
GeoShapeField(
"$.geom", as_name="geom", coord_system=GeoShapeField.FLAT
)
)
geom_index_create_result = r.ft("geomidx").create_index(
geom_schema,
definition=IndexDefinition(
prefix=["shape:"], index_type=IndexType.JSON
)
)
print(geom_index_create_result) # True
shape1 = {
"name": "Green Square",
"geom": "POLYGON ((1 1, 1 3, 3 3, 3 1, 1 1))"
}
gm_json_res_1 = r.json().set("shape:1", Path.root_path(), shape1)
print(gm_json_res_1) # >>> True
shape2 = {
"name": "Red Rectangle",
"geom": "POLYGON ((2 2.5, 2 3.5, 3.5 3.5, 3.5 2.5, 2 2.5))"
}
gm_json_res_2 = r.json().set("shape:2", Path.root_path(), shape2)
print(gm_json_res_2) # >>> True
shape3 = {
"name": "Blue Triangle",
"geom": "POLYGON ((3.5 1, 3.75 2, 4 1, 3.5 1))"
}
gm_json_res_3 = r.json().set("shape:3", Path.root_path(), shape3)
print(gm_json_res_3) # >>> True
shape4 = {
"name": "Purple Point",
"geom": "POINT (2 2)"
}
gm_json_res_4 = r.json().set("shape:4", Path.root_path(), shape4)
print(gm_json_res_4) # >>> True
geom_result = r.ft("geomidx").search(
Query(
"(-@name:(Green Square) @geom:[WITHIN $qshape])"
).dialect(4).paging(0, 1),
query_params={
"qshape": "POLYGON ((1 1, 1 3, 3 3, 3 1, 1 1))"
}
)
print(geom_result)
# >>> Result{1 total, docs: [Document {'id': 'shape:4'...
import org.json.JSONObject;
import redis.clients.jedis.UnifiedJedis;
import redis.clients.jedis.json.Path2;
import redis.clients.jedis.search.Document;
import redis.clients.jedis.search.FTCreateParams;
import redis.clients.jedis.search.FTSearchParams;
import redis.clients.jedis.search.IndexDataType;
import redis.clients.jedis.search.schemafields.*;
import redis.clients.jedis.search.schemafields.GeoShapeField.CoordinateSystem;
import redis.clients.jedis.search.SearchResult;
import redis.clients.jedis.exceptions.JedisDataException;
import static org.junit.jupiter.api.Assertions.assertEquals;
public class GeoIndexExample {
public void run() {
UnifiedJedis jedis = new UnifiedJedis("redis://localhost:6379");
SchemaField[] geoSchema = {
GeoField.of("$.location").as("location")
};
String geoIdxCreateResult = jedis.ftCreate("productidx",
FTCreateParams.createParams()
.on(IndexDataType.JSON)
.addPrefix("product:"),
geoSchema
);
JSONObject prd46885 = new JSONObject()
.put("description", "Navy Blue Slippers")
.put("price", 45.99)
.put("city", "Denver")
.put("location", "-104.991531, 39.742043");
String jsonAddResult1 = jedis.jsonSet("product:46885", new Path2("$"), prd46885);
System.out.println(jsonAddResult1); // >>> OK
JSONObject prd46886 = new JSONObject()
.put("description", "Bright Green Socks")
.put("price", 25.50)
.put("city", "Fort Collins")
.put("location", "-105.0618814,40.5150098");
String jsonAddResult2 = jedis.jsonSet("product:46886", new Path2("$"), prd46886);
System.out.println(jsonAddResult2); // >>> OK
SearchResult geoResult = jedis.ftSearch("productidx",
"@location:[-104.800644 38.846127 100 mi]"
);
System.out.println(geoResult.getTotalResults()); // >>> 1
for (Document doc: geoResult.getDocuments()) {
System.out.println(doc.getId());
}
// >>> product:46885
SchemaField[] geomSchema = {
TextField.of("$.name").as("name"),
GeoShapeField.of("$.geom", CoordinateSystem.FLAT).as("geom")
};
String geomIndexCreateResult = jedis.ftCreate("geomidx",
FTCreateParams.createParams()
.on(IndexDataType.JSON)
.addPrefix("shape"),
geomSchema
);
System.out.println(geomIndexCreateResult); // >>> OK
JSONObject shape1 = new JSONObject()
.put("name", "Green Square")
.put("geom", "POLYGON ((1 1, 1 3, 3 3, 3 1, 1 1))");
String gmJsonRes1 = jedis.jsonSet("shape:1", new Path2("$"), shape1);
System.out.println(gmJsonRes1); // >>> OK
JSONObject shape2 = new JSONObject()
.put("name", "Red Rectangle")
.put("geom", "POLYGON ((2 2.5, 2 3.5, 3.5 3.5, 3.5 2.5, 2 2.5))");
String gmJsonRes2 = jedis.jsonSet("shape:2", new Path2("$"), shape2);
System.out.println(gmJsonRes2); // >>> OK
JSONObject shape3 = new JSONObject()
.put("name", "Blue Triangle")
.put("geom", "POLYGON ((3.5 1, 3.75 2, 4 1, 3.5 1))");
String gmJsonRes3 = jedis.jsonSet("shape:3", new Path2("$"), shape3);
System.out.println(gmJsonRes3); // >>> OK
JSONObject shape4 = new JSONObject()
.put("name", "Purple Point")
.put("geom", "POINT (2 2)");
String gmJsonRes4 = jedis.jsonSet("shape:4", new Path2("$"), shape4);
System.out.println(gmJsonRes4); // >>> OK
SearchResult geomResult = jedis.ftSearch("geomidx",
"(-@name:(Green Square) @geom:[WITHIN $qshape])",
FTSearchParams.searchParams()
.addParam("qshape", "POLYGON ((1 1, 1 3, 3 3, 3 1, 1 1))")
.dialect(4)
.limit(0, 1)
);
System.out.println(geomResult.getTotalResults()); // >>> 1
for (Document doc: geomResult.getDocuments()) {
System.out.println(doc.getId());
}
// shape:4
jedis.close();
}
}
package example_commands_test
import (
"context"
"fmt"
"github.com/redis/go-redis/v9"
)
func ExampleClient_geoindex() {
ctx := context.Background()
rdb := redis.NewClient(&redis.Options{
Addr: "localhost:6379",
Password: "", // no password docs
DB: 0, // use default DB
Protocol: 2,
})
geoCreateResult, err := rdb.FTCreate(ctx,
"productidx",
&redis.FTCreateOptions{
OnJSON: true,
Prefix: []interface{}{"product:"},
},
&redis.FieldSchema{
FieldName: "$.location",
As: "location",
FieldType: redis.SearchFieldTypeGeo,
},
).Result()
if err != nil {
panic(err)
}
fmt.Println(geoCreateResult) // >>> OK
prd46885 := map[string]interface{}{
"description": "Navy Blue Slippers",
"price": 45.99,
"city": "Denver",
"location": "-104.991531, 39.742043",
}
gjResult1, err := rdb.JSONSet(ctx, "product:46885", "$", prd46885).Result()
if err != nil {
panic(err)
}
fmt.Println(gjResult1) // >>> OK
prd46886 := map[string]interface{}{
"description": "Bright Green Socks",
"price": 25.50,
"city": "Fort Collins",
"location": "-105.0618814,40.5150098",
}
gjResult2, err := rdb.JSONSet(ctx, "product:46886", "$", prd46886).Result()
if err != nil {
panic(err)
}
fmt.Println(gjResult2) // >>> OK
geoQueryResult, err := rdb.FTSearch(ctx, "productidx",
"@location:[-104.800644 38.846127 100 mi]",
).Result()
if err != nil {
panic(err)
}
fmt.Println(geoQueryResult)
// >>> {1 [{product:46885...
geomCreateResult, err := rdb.FTCreate(ctx, "geomidx",
&redis.FTCreateOptions{
OnJSON: true,
Prefix: []interface{}{"shape:"},
},
&redis.FieldSchema{
FieldName: "$.name",
As: "name",
FieldType: redis.SearchFieldTypeText,
},
&redis.FieldSchema{
FieldName: "$.geom",
As: "geom",
FieldType: redis.SearchFieldTypeGeoShape,
GeoShapeFieldType: "FLAT",
},
).Result()
if err != nil {
panic(err)
}
fmt.Println(geomCreateResult) // >>> OK
shape1 := map[string]interface{}{
"name": "Green Square",
"geom": "POLYGON ((1 1, 1 3, 3 3, 3 1, 1 1))",
}
gmjResult1, err := rdb.JSONSet(ctx, "shape:1", "$", shape1).Result()
if err != nil {
panic(err)
}
fmt.Println(gmjResult1) // >>> OK
shape2 := map[string]interface{}{
"name": "Red Rectangle",
"geom": "POLYGON ((2 2.5, 2 3.5, 3.5 3.5, 3.5 2.5, 2 2.5))",
}
gmjResult2, err := rdb.JSONSet(ctx, "shape:2", "$", shape2).Result()
if err != nil {
panic(err)
}
fmt.Println(gmjResult2) // >>> OK
shape3 := map[string]interface{}{
"name": "Blue Triangle",
"geom": "POLYGON ((3.5 1, 3.75 2, 4 1, 3.5 1))",
}
gmjResult3, err := rdb.JSONSet(ctx, "shape:3", "$", shape3).Result()
if err != nil {
panic(err)
}
fmt.Println(gmjResult3) // >>> OK
shape4 := map[string]interface{}{
"name": "Purple Point",
"geom": "POINT (2 2)",
}
gmjResult4, err := rdb.JSONSet(ctx, "shape:4", "$", shape4).Result()
if err != nil {
panic(err)
}
fmt.Println(gmjResult4) // >>> OK
geomQueryResult, err := rdb.FTSearchWithArgs(ctx, "geomidx",
"(-@name:(Green Square) @geom:[WITHIN $qshape])",
&redis.FTSearchOptions{
Params: map[string]interface{}{
"qshape": "POLYGON ((1 1, 1 3, 3 3, 3 1, 1 1))",
},
DialectVersion: 4,
Limit: 1,
},
).Result()
if err != nil {
panic(err)
}
fmt.Println(geomQueryResult)
// >>> {1 [{shape:4...
}
对 JSON 对象使用 shape:
前缀将其添加到索引中
> JSON.SET shape:1 $ '{"name": "Green Square", "geom": "POLYGON ((1 1, 1 3, 3 3, 3 1, 1 1))"}'
OK
> JSON.SET shape:2 $ '{"name": "Red Rectangle", "geom": "POLYGON ((2 2.5, 2 3.5, 3.5 3.5, 3.5 2.5, 2 2.5))"}'
OK
> JSON.SET shape:3 $ '{"name": "Blue Triangle", "geom": "POLYGON ((3.5 1, 3.75 2, 4 1, 3.5 1))"}'
OK
> JSON.SET shape:4 $ '{"name": "Purple Point", "geom": "POINT (2 2)"}'
OK
您是否厌倦了使用 redis-cli?试试 Redis Insight - Redis 开发者 GUI。
import redis
from redis.commands.json.path import Path
from redis.commands.search.field import TextField, GeoField, GeoShapeField
from redis.commands.search.indexDefinition import IndexDefinition, IndexType
from redis.commands.search.query import Query
r = redis.Redis()
geo_schema = (
GeoField("$.location", as_name="location")
)
geo_index_create_result = r.ft("productidx").create_index(
geo_schema,
definition=IndexDefinition(
prefix=["product:"], index_type=IndexType.JSON
)
)
print(geo_index_create_result) # >>> True
prd46885 = {
"description": "Navy Blue Slippers",
"price": 45.99,
"city": "Denver",
"location": "-104.991531, 39.742043"
}
json_add_result_1 = r.json().set("product:46885", Path.root_path(), prd46885)
print(json_add_result_1) # >>> True
prd46886 = {
"description": "Bright Green Socks",
"price": 25.50,
"city": "Fort Collins",
"location": "-105.0618814,40.5150098"
}
json_add_result_2 = r.json().set("product:46886", Path.root_path(), prd46886)
print(json_add_result_2) # >>> True
geo_result = r.ft("productidx").search(
"@location:[-104.800644 38.846127 100 mi]"
)
print(geo_result)
# >>> Result{1 total, docs: [Document {'id': 'product:46885'...
geom_schema = (
TextField("$.name", as_name="name"),
GeoShapeField(
"$.geom", as_name="geom", coord_system=GeoShapeField.FLAT
)
)
geom_index_create_result = r.ft("geomidx").create_index(
geom_schema,
definition=IndexDefinition(
prefix=["shape:"], index_type=IndexType.JSON
)
)
print(geom_index_create_result) # True
shape1 = {
"name": "Green Square",
"geom": "POLYGON ((1 1, 1 3, 3 3, 3 1, 1 1))"
}
gm_json_res_1 = r.json().set("shape:1", Path.root_path(), shape1)
print(gm_json_res_1) # >>> True
shape2 = {
"name": "Red Rectangle",
"geom": "POLYGON ((2 2.5, 2 3.5, 3.5 3.5, 3.5 2.5, 2 2.5))"
}
gm_json_res_2 = r.json().set("shape:2", Path.root_path(), shape2)
print(gm_json_res_2) # >>> True
shape3 = {
"name": "Blue Triangle",
"geom": "POLYGON ((3.5 1, 3.75 2, 4 1, 3.5 1))"
}
gm_json_res_3 = r.json().set("shape:3", Path.root_path(), shape3)
print(gm_json_res_3) # >>> True
shape4 = {
"name": "Purple Point",
"geom": "POINT (2 2)"
}
gm_json_res_4 = r.json().set("shape:4", Path.root_path(), shape4)
print(gm_json_res_4) # >>> True
geom_result = r.ft("geomidx").search(
Query(
"(-@name:(Green Square) @geom:[WITHIN $qshape])"
).dialect(4).paging(0, 1),
query_params={
"qshape": "POLYGON ((1 1, 1 3, 3 3, 3 1, 1 1))"
}
)
print(geom_result)
# >>> Result{1 total, docs: [Document {'id': 'shape:4'...
import org.json.JSONObject;
import redis.clients.jedis.UnifiedJedis;
import redis.clients.jedis.json.Path2;
import redis.clients.jedis.search.Document;
import redis.clients.jedis.search.FTCreateParams;
import redis.clients.jedis.search.FTSearchParams;
import redis.clients.jedis.search.IndexDataType;
import redis.clients.jedis.search.schemafields.*;
import redis.clients.jedis.search.schemafields.GeoShapeField.CoordinateSystem;
import redis.clients.jedis.search.SearchResult;
import redis.clients.jedis.exceptions.JedisDataException;
import static org.junit.jupiter.api.Assertions.assertEquals;
public class GeoIndexExample {
public void run() {
UnifiedJedis jedis = new UnifiedJedis("redis://localhost:6379");
SchemaField[] geoSchema = {
GeoField.of("$.location").as("location")
};
String geoIdxCreateResult = jedis.ftCreate("productidx",
FTCreateParams.createParams()
.on(IndexDataType.JSON)
.addPrefix("product:"),
geoSchema
);
JSONObject prd46885 = new JSONObject()
.put("description", "Navy Blue Slippers")
.put("price", 45.99)
.put("city", "Denver")
.put("location", "-104.991531, 39.742043");
String jsonAddResult1 = jedis.jsonSet("product:46885", new Path2("$"), prd46885);
System.out.println(jsonAddResult1); // >>> OK
JSONObject prd46886 = new JSONObject()
.put("description", "Bright Green Socks")
.put("price", 25.50)
.put("city", "Fort Collins")
.put("location", "-105.0618814,40.5150098");
String jsonAddResult2 = jedis.jsonSet("product:46886", new Path2("$"), prd46886);
System.out.println(jsonAddResult2); // >>> OK
SearchResult geoResult = jedis.ftSearch("productidx",
"@location:[-104.800644 38.846127 100 mi]"
);
System.out.println(geoResult.getTotalResults()); // >>> 1
for (Document doc: geoResult.getDocuments()) {
System.out.println(doc.getId());
}
// >>> product:46885
SchemaField[] geomSchema = {
TextField.of("$.name").as("name"),
GeoShapeField.of("$.geom", CoordinateSystem.FLAT).as("geom")
};
String geomIndexCreateResult = jedis.ftCreate("geomidx",
FTCreateParams.createParams()
.on(IndexDataType.JSON)
.addPrefix("shape"),
geomSchema
);
System.out.println(geomIndexCreateResult); // >>> OK
JSONObject shape1 = new JSONObject()
.put("name", "Green Square")
.put("geom", "POLYGON ((1 1, 1 3, 3 3, 3 1, 1 1))");
String gmJsonRes1 = jedis.jsonSet("shape:1", new Path2("$"), shape1);
System.out.println(gmJsonRes1); // >>> OK
JSONObject shape2 = new JSONObject()
.put("name", "Red Rectangle")
.put("geom", "POLYGON ((2 2.5, 2 3.5, 3.5 3.5, 3.5 2.5, 2 2.5))");
String gmJsonRes2 = jedis.jsonSet("shape:2", new Path2("$"), shape2);
System.out.println(gmJsonRes2); // >>> OK
JSONObject shape3 = new JSONObject()
.put("name", "Blue Triangle")
.put("geom", "POLYGON ((3.5 1, 3.75 2, 4 1, 3.5 1))");
String gmJsonRes3 = jedis.jsonSet("shape:3", new Path2("$"), shape3);
System.out.println(gmJsonRes3); // >>> OK
JSONObject shape4 = new JSONObject()
.put("name", "Purple Point")
.put("geom", "POINT (2 2)");
String gmJsonRes4 = jedis.jsonSet("shape:4", new Path2("$"), shape4);
System.out.println(gmJsonRes4); // >>> OK
SearchResult geomResult = jedis.ftSearch("geomidx",
"(-@name:(Green Square) @geom:[WITHIN $qshape])",
FTSearchParams.searchParams()
.addParam("qshape", "POLYGON ((1 1, 1 3, 3 3, 3 1, 1 1))")
.dialect(4)
.limit(0, 1)
);
System.out.println(geomResult.getTotalResults()); // >>> 1
for (Document doc: geomResult.getDocuments()) {
System.out.println(doc.getId());
}
// shape:4
jedis.close();
}
}
package example_commands_test
import (
"context"
"fmt"
"github.com/redis/go-redis/v9"
)
func ExampleClient_geoindex() {
ctx := context.Background()
rdb := redis.NewClient(&redis.Options{
Addr: "localhost:6379",
Password: "", // no password docs
DB: 0, // use default DB
Protocol: 2,
})
geoCreateResult, err := rdb.FTCreate(ctx,
"productidx",
&redis.FTCreateOptions{
OnJSON: true,
Prefix: []interface{}{"product:"},
},
&redis.FieldSchema{
FieldName: "$.location",
As: "location",
FieldType: redis.SearchFieldTypeGeo,
},
).Result()
if err != nil {
panic(err)
}
fmt.Println(geoCreateResult) // >>> OK
prd46885 := map[string]interface{}{
"description": "Navy Blue Slippers",
"price": 45.99,
"city": "Denver",
"location": "-104.991531, 39.742043",
}
gjResult1, err := rdb.JSONSet(ctx, "product:46885", "$", prd46885).Result()
if err != nil {
panic(err)
}
fmt.Println(gjResult1) // >>> OK
prd46886 := map[string]interface{}{
"description": "Bright Green Socks",
"price": 25.50,
"city": "Fort Collins",
"location": "-105.0618814,40.5150098",
}
gjResult2, err := rdb.JSONSet(ctx, "product:46886", "$", prd46886).Result()
if err != nil {
panic(err)
}
fmt.Println(gjResult2) // >>> OK
geoQueryResult, err := rdb.FTSearch(ctx, "productidx",
"@location:[-104.800644 38.846127 100 mi]",
).Result()
if err != nil {
panic(err)
}
fmt.Println(geoQueryResult)
// >>> {1 [{product:46885...
geomCreateResult, err := rdb.FTCreate(ctx, "geomidx",
&redis.FTCreateOptions{
OnJSON: true,
Prefix: []interface{}{"shape:"},
},
&redis.FieldSchema{
FieldName: "$.name",
As: "name",
FieldType: redis.SearchFieldTypeText,
},
&redis.FieldSchema{
FieldName: "$.geom",
As: "geom",
FieldType: redis.SearchFieldTypeGeoShape,
GeoShapeFieldType: "FLAT",
},
).Result()
if err != nil {
panic(err)
}
fmt.Println(geomCreateResult) // >>> OK
shape1 := map[string]interface{}{
"name": "Green Square",
"geom": "POLYGON ((1 1, 1 3, 3 3, 3 1, 1 1))",
}
gmjResult1, err := rdb.JSONSet(ctx, "shape:1", "$", shape1).Result()
if err != nil {
panic(err)
}
fmt.Println(gmjResult1) // >>> OK
shape2 := map[string]interface{}{
"name": "Red Rectangle",
"geom": "POLYGON ((2 2.5, 2 3.5, 3.5 3.5, 3.5 2.5, 2 2.5))",
}
gmjResult2, err := rdb.JSONSet(ctx, "shape:2", "$", shape2).Result()
if err != nil {
panic(err)
}
fmt.Println(gmjResult2) // >>> OK
shape3 := map[string]interface{}{
"name": "Blue Triangle",
"geom": "POLYGON ((3.5 1, 3.75 2, 4 1, 3.5 1))",
}
gmjResult3, err := rdb.JSONSet(ctx, "shape:3", "$", shape3).Result()
if err != nil {
panic(err)
}
fmt.Println(gmjResult3) // >>> OK
shape4 := map[string]interface{}{
"name": "Purple Point",
"geom": "POINT (2 2)",
}
gmjResult4, err := rdb.JSONSet(ctx, "shape:4", "$", shape4).Result()
if err != nil {
panic(err)
}
fmt.Println(gmjResult4) // >>> OK
geomQueryResult, err := rdb.FTSearchWithArgs(ctx, "geomidx",
"(-@name:(Green Square) @geom:[WITHIN $qshape])",
&redis.FTSearchOptions{
Params: map[string]interface{}{
"qshape": "POLYGON ((1 1, 1 3, 3 3, 3 1, 1 1))",
},
DialectVersion: 4,
Limit: 1,
},
).Result()
if err != nil {
panic(err)
}
fmt.Println(geomQueryResult)
// >>> {1 [{shape:4...
}
您现在可以对索引运行各种地理空间查询。例如,以下查询返回绿色方框边界内的任何形状,但省略绿色方框本身
> FT.SEARCH geomidx "(-@name:(Green Square) @geom:[WITHIN $qshape])" PARAMS 2 qshape "POLYGON ((1 1, 1 3, 3 3, 3 1, 1 1))" RETURN 1 name DIALECT 2
1) (integer) 1
2) "shape:4"
3) 1) "name"
2) "[\"Purple Point\"]"
您是否厌倦了使用 redis-cli?试试 Redis Insight - Redis 开发者 GUI。
import redis
from redis.commands.json.path import Path
from redis.commands.search.field import TextField, GeoField, GeoShapeField
from redis.commands.search.indexDefinition import IndexDefinition, IndexType
from redis.commands.search.query import Query
r = redis.Redis()
geo_schema = (
GeoField("$.location", as_name="location")
)
geo_index_create_result = r.ft("productidx").create_index(
geo_schema,
definition=IndexDefinition(
prefix=["product:"], index_type=IndexType.JSON
)
)
print(geo_index_create_result) # >>> True
prd46885 = {
"description": "Navy Blue Slippers",
"price": 45.99,
"city": "Denver",
"location": "-104.991531, 39.742043"
}
json_add_result_1 = r.json().set("product:46885", Path.root_path(), prd46885)
print(json_add_result_1) # >>> True
prd46886 = {
"description": "Bright Green Socks",
"price": 25.50,
"city": "Fort Collins",
"location": "-105.0618814,40.5150098"
}
json_add_result_2 = r.json().set("product:46886", Path.root_path(), prd46886)
print(json_add_result_2) # >>> True
geo_result = r.ft("productidx").search(
"@location:[-104.800644 38.846127 100 mi]"
)
print(geo_result)
# >>> Result{1 total, docs: [Document {'id': 'product:46885'...
geom_schema = (
TextField("$.name", as_name="name"),
GeoShapeField(
"$.geom", as_name="geom", coord_system=GeoShapeField.FLAT
)
)
geom_index_create_result = r.ft("geomidx").create_index(
geom_schema,
definition=IndexDefinition(
prefix=["shape:"], index_type=IndexType.JSON
)
)
print(geom_index_create_result) # True
shape1 = {
"name": "Green Square",
"geom": "POLYGON ((1 1, 1 3, 3 3, 3 1, 1 1))"
}
gm_json_res_1 = r.json().set("shape:1", Path.root_path(), shape1)
print(gm_json_res_1) # >>> True
shape2 = {
"name": "Red Rectangle",
"geom": "POLYGON ((2 2.5, 2 3.5, 3.5 3.5, 3.5 2.5, 2 2.5))"
}
gm_json_res_2 = r.json().set("shape:2", Path.root_path(), shape2)
print(gm_json_res_2) # >>> True
shape3 = {
"name": "Blue Triangle",
"geom": "POLYGON ((3.5 1, 3.75 2, 4 1, 3.5 1))"
}
gm_json_res_3 = r.json().set("shape:3", Path.root_path(), shape3)
print(gm_json_res_3) # >>> True
shape4 = {
"name": "Purple Point",
"geom": "POINT (2 2)"
}
gm_json_res_4 = r.json().set("shape:4", Path.root_path(), shape4)
print(gm_json_res_4) # >>> True
geom_result = r.ft("geomidx").search(
Query(
"(-@name:(Green Square) @geom:[WITHIN $qshape])"
).dialect(4).paging(0, 1),
query_params={
"qshape": "POLYGON ((1 1, 1 3, 3 3, 3 1, 1 1))"
}
)
print(geom_result)
# >>> Result{1 total, docs: [Document {'id': 'shape:4'...
import org.json.JSONObject;
import redis.clients.jedis.UnifiedJedis;
import redis.clients.jedis.json.Path2;
import redis.clients.jedis.search.Document;
import redis.clients.jedis.search.FTCreateParams;
import redis.clients.jedis.search.FTSearchParams;
import redis.clients.jedis.search.IndexDataType;
import redis.clients.jedis.search.schemafields.*;
import redis.clients.jedis.search.schemafields.GeoShapeField.CoordinateSystem;
import redis.clients.jedis.search.SearchResult;
import redis.clients.jedis.exceptions.JedisDataException;
import static org.junit.jupiter.api.Assertions.assertEquals;
public class GeoIndexExample {
public void run() {
UnifiedJedis jedis = new UnifiedJedis("redis://localhost:6379");
SchemaField[] geoSchema = {
GeoField.of("$.location").as("location")
};
String geoIdxCreateResult = jedis.ftCreate("productidx",
FTCreateParams.createParams()
.on(IndexDataType.JSON)
.addPrefix("product:"),
geoSchema
);
JSONObject prd46885 = new JSONObject()
.put("description", "Navy Blue Slippers")
.put("price", 45.99)
.put("city", "Denver")
.put("location", "-104.991531, 39.742043");
String jsonAddResult1 = jedis.jsonSet("product:46885", new Path2("$"), prd46885);
System.out.println(jsonAddResult1); // >>> OK
JSONObject prd46886 = new JSONObject()
.put("description", "Bright Green Socks")
.put("price", 25.50)
.put("city", "Fort Collins")
.put("location", "-105.0618814,40.5150098");
String jsonAddResult2 = jedis.jsonSet("product:46886", new Path2("$"), prd46886);
System.out.println(jsonAddResult2); // >>> OK
SearchResult geoResult = jedis.ftSearch("productidx",
"@location:[-104.800644 38.846127 100 mi]"
);
System.out.println(geoResult.getTotalResults()); // >>> 1
for (Document doc: geoResult.getDocuments()) {
System.out.println(doc.getId());
}
// >>> product:46885
SchemaField[] geomSchema = {
TextField.of("$.name").as("name"),
GeoShapeField.of("$.geom", CoordinateSystem.FLAT).as("geom")
};
String geomIndexCreateResult = jedis.ftCreate("geomidx",
FTCreateParams.createParams()
.on(IndexDataType.JSON)
.addPrefix("shape"),
geomSchema
);
System.out.println(geomIndexCreateResult); // >>> OK
JSONObject shape1 = new JSONObject()
.put("name", "Green Square")
.put("geom", "POLYGON ((1 1, 1 3, 3 3, 3 1, 1 1))");
String gmJsonRes1 = jedis.jsonSet("shape:1", new Path2("$"), shape1);
System.out.println(gmJsonRes1); // >>> OK
JSONObject shape2 = new JSONObject()
.put("name", "Red Rectangle")
.put("geom", "POLYGON ((2 2.5, 2 3.5, 3.5 3.5, 3.5 2.5, 2 2.5))");
String gmJsonRes2 = jedis.jsonSet("shape:2", new Path2("$"), shape2);
System.out.println(gmJsonRes2); // >>> OK
JSONObject shape3 = new JSONObject()
.put("name", "Blue Triangle")
.put("geom", "POLYGON ((3.5 1, 3.75 2, 4 1, 3.5 1))");
String gmJsonRes3 = jedis.jsonSet("shape:3", new Path2("$"), shape3);
System.out.println(gmJsonRes3); // >>> OK
JSONObject shape4 = new JSONObject()
.put("name", "Purple Point")
.put("geom", "POINT (2 2)");
String gmJsonRes4 = jedis.jsonSet("shape:4", new Path2("$"), shape4);
System.out.println(gmJsonRes4); // >>> OK
SearchResult geomResult = jedis.ftSearch("geomidx",
"(-@name:(Green Square) @geom:[WITHIN $qshape])",
FTSearchParams.searchParams()
.addParam("qshape", "POLYGON ((1 1, 1 3, 3 3, 3 1, 1 1))")
.dialect(4)
.limit(0, 1)
);
System.out.println(geomResult.getTotalResults()); // >>> 1
for (Document doc: geomResult.getDocuments()) {
System.out.println(doc.getId());
}
// shape:4
jedis.close();
}
}
package example_commands_test
import (
"context"
"fmt"
"github.com/redis/go-redis/v9"
)
func ExampleClient_geoindex() {
ctx := context.Background()
rdb := redis.NewClient(&redis.Options{
Addr: "localhost:6379",
Password: "", // no password docs
DB: 0, // use default DB
Protocol: 2,
})
geoCreateResult, err := rdb.FTCreate(ctx,
"productidx",
&redis.FTCreateOptions{
OnJSON: true,
Prefix: []interface{}{"product:"},
},
&redis.FieldSchema{
FieldName: "$.location",
As: "location",
FieldType: redis.SearchFieldTypeGeo,
},
).Result()
if err != nil {
panic(err)
}
fmt.Println(geoCreateResult) // >>> OK
prd46885 := map[string]interface{}{
"description": "Navy Blue Slippers",
"price": 45.99,
"city": "Denver",
"location": "-104.991531, 39.742043",
}
gjResult1, err := rdb.JSONSet(ctx, "product:46885", "$", prd46885).Result()
if err != nil {
panic(err)
}
fmt.Println(gjResult1) // >>> OK
prd46886 := map[string]interface{}{
"description": "Bright Green Socks",
"price": 25.50,
"city": "Fort Collins",
"location": "-105.0618814,40.5150098",
}
gjResult2, err := rdb.JSONSet(ctx, "product:46886", "$", prd46886).Result()
if err != nil {
panic(err)
}
fmt.Println(gjResult2) // >>> OK
geoQueryResult, err := rdb.FTSearch(ctx, "productidx",
"@location:[-104.800644 38.846127 100 mi]",
).Result()
if err != nil {
panic(err)
}
fmt.Println(geoQueryResult)
// >>> {1 [{product:46885...
geomCreateResult, err := rdb.FTCreate(ctx, "geomidx",
&redis.FTCreateOptions{
OnJSON: true,
Prefix: []interface{}{"shape:"},
},
&redis.FieldSchema{
FieldName: "$.name",
As: "name",
FieldType: redis.SearchFieldTypeText,
},
&redis.FieldSchema{
FieldName: "$.geom",
As: "geom",
FieldType: redis.SearchFieldTypeGeoShape,
GeoShapeFieldType: "FLAT",
},
).Result()
if err != nil {
panic(err)
}
fmt.Println(geomCreateResult) // >>> OK
shape1 := map[string]interface{}{
"name": "Green Square",
"geom": "POLYGON ((1 1, 1 3, 3 3, 3 1, 1 1))",
}
gmjResult1, err := rdb.JSONSet(ctx, "shape:1", "$", shape1).Result()
if err != nil {
panic(err)
}
fmt.Println(gmjResult1) // >>> OK
shape2 := map[string]interface{}{
"name": "Red Rectangle",
"geom": "POLYGON ((2 2.5, 2 3.5, 3.5 3.5, 3.5 2.5, 2 2.5))",
}
gmjResult2, err := rdb.JSONSet(ctx, "shape:2", "$", shape2).Result()
if err != nil {
panic(err)
}
fmt.Println(gmjResult2) // >>> OK
shape3 := map[string]interface{}{
"name": "Blue Triangle",
"geom": "POLYGON ((3.5 1, 3.75 2, 4 1, 3.5 1))",
}
gmjResult3, err := rdb.JSONSet(ctx, "shape:3", "$", shape3).Result()
if err != nil {
panic(err)
}
fmt.Println(gmjResult3) // >>> OK
shape4 := map[string]interface{}{
"name": "Purple Point",
"geom": "POINT (2 2)",
}
gmjResult4, err := rdb.JSONSet(ctx, "shape:4", "$", shape4).Result()
if err != nil {
panic(err)
}
fmt.Println(gmjResult4) // >>> OK
geomQueryResult, err := rdb.FTSearchWithArgs(ctx, "geomidx",
"(-@name:(Green Square) @geom:[WITHIN $qshape])",
&redis.FTSearchOptions{
Params: map[string]interface{}{
"qshape": "POLYGON ((1 1, 1 3, 3 3, 3 1, 1 1))",
},
DialectVersion: 4,
Limit: 1,
},
).Result()
if err != nil {
panic(err)
}
fmt.Println(geomQueryResult)
// >>> {1 [{shape:4...
}
您还可以运行查询来查找索引中的形状是否完全包含或相互重叠。有关更多信息,请参阅地理空间查询。