distance

更新时间:
复制 MD 格式

Compatibility

This function can be used in filter, sort, and formula expressions.

You must configure the document fields used as function parameters as an index or a property. For more information, see the relevant function documentation.

distance: Calculates the spherical distance between two points. It is commonly used for distance calculations in location-based services (LBS).

  1. 1. Usage notes:

  2. distance(longitude_a, latitude_a, longitude_b, latitude_b, output_name)

  3. Parameters:

    • longitude_a: The longitude of point A. This parameter must be a field of the floating-point type.

    • latitude_a: The latitude of point A. This parameter must be a field of the floating-point type.

    • longitude_b: The longitude of point B. This parameter can be a field of the floating-point type or a value set in the kvpairs clause of the query. The value must be a floating-point number.

    • latitude_b: The latitude of point B. This parameter can be a field of the floating-point type or a value set in the kvpairs clause of the query. The value must be a floating-point number.

    • output_name: Optional. The name for the returned distance value. You can omit this parameter if the distance value does not need to be returned.

  4. 3. The return value is a float.

  5. The distance in kilometers.

  6. 4. Usage Scenarios

  7. Scenario 1: Find restaurants named "Grandma's Home" that are within 10 km of a user at the coordinates (120.34256, 30.56982). The results are sorted by distance from nearest to farthest. In this scenario, lon and lat are fields in the document that store the restaurant's coordinates. You must configure these fields as properties.

  8. # Usage in a sort clause
    query=default:'Grandma's Home'&&
    filter=distance(lon,lat,"120.34256","30.56982")<10&&
    sort=+distance(lon,lat,"120.34256","30.56982")
    
    # Usage for fine sort
    You can also sort by distance by passing the user's coordinates in the kvpairs parameter.
    kvpairs=longitude_in_query:120.34256,latitude_in_query:30.56982
    Fine sort expression: distance(longitude_in_doc, latitude_in_doc, longitude_in_query, latitude_in_query, distance_value)

Notes:

  • The fields used as function parameters must be configured as properties.

  • The output_name parameter can be used only in a fine sort expression. It is not supported in filter or sort clauses. When you specify the output_name parameter, the distance value is returned in the variableValue node. This node is available only if the return format is set to xml or fulljson. You can set the return format using the format parameter in the config clause.