You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何修改Vespa最近邻搜索结果的距离排序为升序?

Vespa 近邻查询结果改为距离升序的解决方案

问题背景

我有如下Vespa Schema:

schema embeddings {
  document embeddings {
    field id type int {}
    field text_embedding type tensor<double>(d0[960]) {
      indexing: attribute
      attribute {
        distance-metric: euclidean
      }
    }
  }

  rank-profile distance {
    num-threads-per-search:1
    inputs {
      query(query_embedding) tensor<double>(d0[960])
    }
    first-phase {
      expression: distance(field, text_embedding)
    }
  }
}

使用以下查询体执行查询后,结果按距离降序排列:

body = {
    'yql': 'select * from embeddings where ([{"targetHits":10}] nearestNeighbor(text_embedding, query_embedding));',
    "hits":10,
    'ranking': {
        'profile': 'distance',
        'features': {
            'query(query_embedding)': [...]
        }
    },
}

需要修改查询或Schema,使结果按距离升序排列(已知closeness操作符,需实现特定需求)。


可行解决方案

方案一:修改Rank Profile的排序表达式

Vespa默认以rank分数从高到低排序,当前rank profile用distance(field, text_embedding)作为排序依据,距离越大分数越高,因此结果呈降序。要实现升序,只需将排序表达式改为负的距离值——距离越小,负数值越大,排序时会优先展示:

修改后的Schema中rank-profile部分:

rank-profile distance {
    num-threads-per-search:1
    inputs {
      query(query_embedding) tensor<double>(d0[960])
    }
    first-phase {
      expression: -distance(field, text_embedding)
    }
}

方案二:在查询中直接指定排序规则

无需修改Schema,直接在YQL中添加order by子句,明确指定按距离升序排列:

修改后的查询体YQL字段:

'yql': 'select * from embeddings where ([{"targetHits":10}] nearestNeighbor(text_embedding, query_embedding)) order by distance(text_embedding, query_embedding) asc;',

内容的提问来源于stack exchange,提问作者eawer

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.17 10:05:23