本文介紹向量檢索服務DashVector的資料類型定義。
Doc
@dataclass(frozen=True)
class Doc(object):
id: str # 主鍵
vector: Union[List[int], List[float], np.ndarray] # 向量資料
vectors: Optional[Dict[str, VectorValueType]] = None # 多向量資料
sparse_vector: Optional[Dict[int, float]] = None # 稀疏向量資料
fields: Optional[FieldDataDict] = None # Doc自訂欄位
score: float = 0.0 # 向量相似性@Data
@Builder
public class Doc {
// 主鍵
@NonNull private String id;
// 向量資料
@NonNull private Vector vector;
// 稀疏向量資料
private TreeMap<Integer, Float> sparseVector;
// 文檔自訂欄位
@Builder.Default private Map<String, Object> fields = new HashMap<>();
// 向量相似性
private float score;
// 多向量資料
@Singular
private Map<String, Vector> vectors;
public void addField(String key, String value) {
this.fields.put(key, value);
}
public void addField(String key, Integer value) {
this.fields.put(key, value);
}
public void addField(String key, Float value) {
this.fields.put(key, value);
}
public void addField(String key, Boolean value) {
this.fields.put(key, value);
}
}DocOpResult
@dataclass(frozen=True)
class DocOpResult(object):
doc_op: DocOp
id: str
code: int
message: str@Getter
@Builder
@AllArgsConstructor
@NoArgsConstructor
public class DocOpResult implements Serializable {
@JsonProperty("doc_op")
private com.aliyun.dashvector.proto.DocOpResult.DocOp docOp;
private String id;
private int code;
private String message;
public DocOpResult(com.aliyun.dashvector.proto.DocOpResult docOpResult) {
this.docOp = docOpResult.getDocOp();
this.id = docOpResult.getId();
this.code = docOpResult.getCode();
this.message = docOpResult.getMessage();
}
}CollectionMeta
@dataclass(frozen=True)
class CollectionMeta(object):
name: str # Collection名稱
dimension: int # 向量維度
dtype: str # 向量資料類型,FLOAT/INT
metric: str # 距離度量方式,euclidean/dotproduct/cosine
status: Status # Collection狀態
fields: Dict[str, str] # Collection Fields定義,字典value可選值: FLOAT/BOOL/INT/STRING/LONG/ARRAY_STRING/ARRAY_INT/ARRAY_FLOAT/ARRAY_LONG
partitions: Dict[str, Status] # Collection 分區資訊@Getter
public class CollectionMeta {
// Collection名稱
private final String name;
// 向量維度
private final int dimension;
// 向量資料類型,FLOAT/INT
private final CollectionInfo.DataType dataType;
// 距離度量方式,euclidean/dotproduct/cosine
private final CollectionInfo.Metric metric;
// Collection狀態
private final String status;
// Collection Fields定義,字典value可選值: FLOAT/BOOL/INT/STRING/LONG/ARRAY_STRING/ARRAY_INT/ARRAY_FLOAT/ARRAY_LONG
private final Map<String, FieldType> fieldsSchema;
// Collection 分區資訊
private final Map<String, Status> partitionStatus;
public CollectionMeta(CollectionInfo collectionInfo) {
this.name = collectionInfo.getName();
this.dimension = collectionInfo.getDimension();
this.dataType = collectionInfo.getDtype();
this.metric = collectionInfo.getMetric();
this.status = collectionInfo.getStatus().name();
this.fieldsSchema = collectionInfo.getFieldsSchemaMap();
this.partitionStatus = collectionInfo.getPartitionsMap();
}
}
CollectionStats
@dataclass(frozen=True)
class CollectionStats(object):
total_doc_count: int # Collection 插入資料總量
index_completeness: float # Collection 插入資料完成度
partitions: Dict[str, PartitionStats] # Collection 分區資訊@Getter
public class CollectionStats {
// Collection 插入資料總數
private final long totalDocCount;
// Collection 插入資料完成度
private final float indexCompleteness;
// Collection 分區資訊
private final Map<String, PartitionStats> partitions;
public CollectionStats(StatsCollectionResponse.CollectionStats collectionStats) {
this.totalDocCount = collectionStats.getTotalDocCount();
this.indexCompleteness = collectionStats.getIndexCompleteness();
this.partitions = new HashMap<>();
collectionStats
.getPartitionsMap()
.forEach((key, value) -> this.partitions.put(key, new PartitionStats(value)));
}
}PartitionStats
@dataclass(frozen=True)
class PartitionStats(object):
total_doc_count: int # Partition 分區內資料總量@Getter
public class PartitionStats {
// Partition 分區內資料總量
private final long totalDocCount;
public PartitionStats(com.aliyun.dashvector.proto.PartitionStats partitionStats) {
this.totalDocCount = partitionStats.getTotalDocCount();
}
}
Status
class Status(IntEnum):
INITIALIZED = 0 # Collection/Partition 建立中
SERVING = 1 # Collection/Partition 服務中
DROPPING = 2 # Collection/Partition 刪除中
ERROR = 3 # Collection/Partition 狀態異常Group
@dataclass(frozen=True)
class Group(object):
group_id: str # 分組標識
docs: List[Doc] # 分組下的文檔列表
@Getter
@Builder
public class Group {
// 分組標識
@NonNull private String groupId;
// 分組下的文檔列表
@Singular private List<Doc> docs;
}
RequestUsage
# read_units 和 write_units 是 oneof 關係
class RequestUsage(object):
read_units: int # 讀請求單元數
write_units: int # 寫請求單元數
@Data
@Builder
@JsonInclude(JsonInclude.Include.NON_DEFAULT)
public class RequestUsage {
// 讀請求單元數
private int readUnits;
// 寫請求單元數
private int writeUnits;
}VectorParam
class VectorParam(object):
dimension: int # 向量維度
dtype: Union[Type[int] Type[float]] = float, # 資料類型
metric: str = "cosine" # 距離度量方式
quantize_type: str = "" # 量化類型,參見 https://www.alibabacloud.com/help/zh/vrs/latest/quantification@Builder
@Getter
public class VectorParam {
/** 向量維度 */
private int dimension;
/** 資料類型 */
@Builder.Default @NonNull
private CollectionInfo.DataType dataType = CollectionInfo.DataType.FLOAT;
/** 度量方式 */
@Builder.Default @NonNull
private CollectionInfo.Metric metric = CollectionInfo.Metric.cosine;
/** 量化類型,參見 https://www.alibabacloud.com/help/zh/vrs/latest/quantification */
@Builder.Default
private String quantizeType="";
}VectorQuery
class VectorQuery(object):
vector: VectorValueType # 向量資料
num_candidates: int = 0 # 候選集個數,預設為query參數中的topk
is_linear: bool = False # 是否做線性(暴力)檢索
ef: int = 0 # HNSW檢索時的ef
radius: float = 0.0 # RNN檢索的半徑@Builder
@Getter
public class VectorQuery {
/** 向量資料 */
private Vector vector;
/** 候選集個數,預設為query參數中的topk */
private int numCandidates = 0;
/** 是否做線性(暴力)檢索 */
private boolean linear = false;
/** HNSW檢索時的ef */
private int ef = 0;
/** RNN檢索的半徑 */
private float radius = 0.0F;
}
BaseRanker
融合排序的基類。
class BaseRanker:
pass
public interface Ranker {
com.aliyun.dashvector.proto.Ranker toProto();
}RrfRanker
倒數秩融合排序 (Reciprocal Rank Fusion)根據文檔的排序來計算分數貢獻值,其計算公式如下
其中rank_constant為常數值,預設為60. ranki(doc)為多向量檢索時該文檔在第i條向量召回結果中的排名,其中排名從1開始。
使用RrfRanker時只有排序起作用,原分數不起作用,文檔的最終得分為單個檢索排名得到的分數貢獻值之和。
class RrfRanker(BaseRanker):
def __init__(self, rank_constant: int = 60):
self.rank_constant = rank_constant
@Builder
@Getter
public class RrfRanker implements Ranker {
@Builder.Default
private int rankConstant = 60;
}WeightedRanker
加權融合排序的計算公式如下:
加權融合排序對於單次檢索的分數賦予一個權重。而由於不同距離計算得到的分數的範圍差別很大,為了降低使用者佈建權重的難度,我們在加權之前會對分數做歸一化,歸一化後範圍為[0, 1],其中1表示距離最近,0表示距離最遠。
使用WeightedRanker時只有原分數起作用,排序不起作用,文檔的最終得分為權重與歸一化分數的乘積之和。
權重保持預設值時各個向量的權重均為1.0;否則需要設定每個向量的權重,並且和檢索時的向量必須完全符合。
class WeightedRanker(BaseRanker):
def __init__(self, weights: Optional[Dict[str, float]] = None):
self.weights = weights # 權重值,None表示各個向量的權重相同
@Builder
@Getter
public class WeightedRanker implements Ranker {
private Map<String, Float> weights; // 權重值,null表示各個向量的權重相同
}其他
long = NewType("long", int)
FieldDataType = Union[long, str, int, float, bool, List[long],List[str],List[int],List[float]]
FieldDataDict = Dict[str, FieldDataType]
VectorValueType = Union[List[int], List[float], np.ndarray]