【问题标题】:Spatial Search in Azure Search .NET client APIAzure 搜索 .NET 客户端 API 中的空间搜索
【发布时间】:2020-07-30 22:12:55
【问题描述】:

如何使用 Azure Search .NET SDK 进行空间搜索? REST API 的问题已在此处得到解答:

SO thread for REST API

我怎样才能使用 .NET 客户端 API 做同样的事情?

更具体一点:

如何在 Document 类上定义相应的属性? 如何查询属性值在定义的圆(中心、半径)内的文档?

【问题讨论】:

    标签: azure search geospatial azure-cognitive-search spatial-query


    【解决方案1】:

    在我最后一次尝试中成功了(一如既往,就在发布问题之后......)

    参考 Nuget 包Microsoft.Spatial

    在类定义中使用GeographyPoint作为属性类型:

    public class MyDocument
    {
        [IsFilterable, IsSortable]
        public Microsoft.Spatial.GeographyPoint Location { get; set; }
    }
    

    像这样创建一个文档:

    var lat = ...; //Latitude
    var lng = ...; //Longitude
    var myDoc = new MyDocument();
    
    myDoc.Location = GeographyPoint.Create(lat, lng);
    // Upload to index
    

    这样查询:

    // center of circle to search in
    var lat = ...;
    var lng = ...;
    // radius of circle to search in
    var radius = ...;
    
    // Make sure to use invariant culture to avoid using invalid decimal separators
    var latString = lat.ToString(CultureInfo.InvariantCulture);
    var lngString = lng.ToString(CultureInfo.InvariantCulture);
    var radiusString = radius.ToString(CultureInfo.InvariantCulture);
    
    var searchParams = new SearchParameters();
    searchParams.Filter = $"geo.distance(location, geography'POINT({lngString} {latString})') lt {radius}";
    
    var searchResults = index.Documents.Search<Expert>(keyword, searchParams);
    var items = searchResults.Results.ToList();
    

    请注意,location 对应于属性名称 Location,如果您的属性名称不同,则需要相应地替换。要按距离对结果进行排序,还要设置搜索参数的OrderBy-property:

    searchParams.OrderBy = new List<string> { $"geo.distance(location, geography'POINT({lngString} {latString})') asc" };
    

    我花了一段时间才发现在查询中定义点时:

    geography'POINT({lngString} {latString})'
    

    参数顺序是(Longitude, Latitude),与大多数其他约定不同(即 Google 地图 API 使用其他方式)。

    【讨论】:

      【解决方案2】:

      虽然它会起作用,但接受的答案是不正确的。您确实不需要添加对 Microsoft.Spatial 的引用并使用 GeographicalPoint 类型。

      您只需要创建一个将序列化为 GeoJSON 地理类型的类:

      { “类型”:“点”, “坐标”:[125.6, 10.1] }

      在 C# 中:

      public class GeoPoint
      {
          [JsonProperty("type")]
          public string Type { get; } = "Point";
      
          [JsonProperty("coordinates")]
          public double[] Coordinates { get; set; } = new double[0];
      }
      

      作为索引类中的属性:

          [IsSearchable, IsFilterable]
          [JsonProperty(PropertyNames.Location)]
          public GeoPoint Location { get; set; }
      

      **如果要将其添加为新属性,则需要在重新索引之前在 Azure 门户中添加该属性:

      【讨论】:

        猜你喜欢
        • 2011-05-28
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-10-24
        • 1970-01-01
        • 2022-06-16
        相关资源
        最近更新 更多