您可以使用 Redis OM 进行的一种非常棒的索引是地理索引。要进行地理索引,您只需将模型中的 GeoLoc
字段标记为 Indexed
并创建索引
[Document]
public class Restaurant
{
[Indexed]
public string Name { get; set; }
[Indexed]
public GeoLoc Location{get; set;}
[Indexed(Aggregatable = true)]
public double CostPerPerson{get;set;}
}
所以让我们创建索引并播种一些数据。
// connect
var provider = new RedisConnectionProvider("redis://localhost:6379");
// get connection
var connection = provider.Connection;
// get collection
var restaurants = provider.RedisCollection<Restaurant>();
// Create index
await connection.CreateIndexAsync(typeof(Restaurant));
// seed with dummy data
var r1 = new Restaurant {Name = "Tony's Pizza & Pasta", CostPerPerson = 12.00, Location = new (-122.076751,37.369929)};
var r2 = new Restaurant {Name = "Nizi Sushi", CostPerPerson = 16.00, Location = new (-122.057360,37.371207)};
var r3 = new Restaurant {Name = "Thai Thai", CostPerPerson = 11.50, Location = new (-122.04382,37.38)};
var r4 = new Restaurant {Name = "Chipotles", CostPerPerson = 8.50, Location = new (-122.0524,37.359719 )};
restaurants.Insert(r1);
restaurants.Insert(r2);
restaurants.Insert(r3);
restaurants.Insert(r4);
我们的数据播种完成后,我们现在可以在我们的餐厅数据上运行地理过滤器,假设我们在山景城(例如,Redis 在山景城的办公室位于 -122.064224,37.377266
)有一个办公室,我们想找到附近的餐厅,我们可以使用 GeoFilter
查询在特定半径(例如,1 英里)内的餐厅。
var nearbyRestaurants = restaurants.GeoFilter(x => x.Location, -122.064224, 37.377266, 5, GeoLocDistanceUnit.Miles);
foreach (var restaurant in nearbyRestaurants)
{
Console.WriteLine($"{restaurant.Name} is within 1 mile of work");
}