密集向量数组和余弦相似度

Leo*_*cia 4 vector elasticsearch elasticsearch-query

我想dense_vector在我的文档中存储一个数组,但这对其他数据类型不起作用,例如。

PUT my_index
{
  "mappings": {
    "properties": {
      "my_vectors": {
        "type": "dense_vector",
        "dims": 3  
      },
      "my_text" : {
        "type" : "keyword"
      }
    }
  }
}

PUT my_index/_doc/1
{
  "my_text" : "text1",
  "my_vector" : [[0.5, 10, 6], [-0.5, 10, 10]]
}

Run Code Online (Sandbox Code Playgroud)

返回:

'1 document(s) failed to index.',
    {'_index': 'my_index', '_type': '_doc', '_id': 'some_id', 'status': 400, 'error': 
      {'type': 'mapper_parsing_exception', 'reason': 'failed to parse', 'caused_by': 
        {'type': 'parsing_exception', 
         'reason': 'Failed to parse object: expecting token of type [VALUE_NUMBER] but found [START_ARRAY]'
        }
      }
    }
Run Code Online (Sandbox Code Playgroud)

我如何实现这一目标?不同的文档将具有可变数量的向量,但不会超过少数。

另外,我想通过cosineSimilarity对该数组中的每个值执行 a 来查询它。下面的代码是我通常在文档中只有一个向量时的做法。

"script_score": {
    "query": {
        "match_all": {}
    },
    "script": {
        "source": "(1.0+cosineSimilarity(params.query_vector, doc['my_vectors']))",
        "params": {"query_vector": query_vector}
    }
}
Run Code Online (Sandbox Code Playgroud)

理想情况下,我想要最接近的相似度或平均值。

Gle*_*ith 8

dense_vector数据类型需要像这样每个文档数值之一数组:

PUT my_index/_doc/1
{
  "my_text" : "text1",
  "my_vector" : [0.5, 10, 6]
}
Run Code Online (Sandbox Code Playgroud)

要存储任意数量的向量,您可以将my_vector字段设为“嵌套”类型,其中包含一个对象数组,并且每个对象包含一个向量:

PUT my_index
{
  "mappings": {
    "properties": {
      "my_vectors": {
        "type": "nested",
        "properties": {
          "vector": {
            "type": "dense_vector",
            "dims": 3  
          }
        }
      },
      "my_text" : {
        "type" : "keyword"
      }
    }
  }
}

PUT my_index/_doc/1
{
  "my_text" : "text1",
  "my_vector" : [
    {"vector": [0.5, 10, 6]}, 
    {"vector": [-0.5, 10, 10]}
  ]
}
Run Code Online (Sandbox Code Playgroud)

编辑

然后,要查询文档,您可以使用以下内容(从 ES v7.6.1 开始)

{
  "query": {
    "nested": {
      "path": "my_vectors",
      "score_mode": "max", 
      "query": {
        "function_score": {
          "script_score": {
            "script": {
              "source": "(1.0+cosineSimilarity(params.query_vector, 'my_vectors.vector'))",
              "params": {"query_vector": query_vector}
            }
          }
        }
      }
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

需要注意的几点:

  • 查询需要包含在nested声明中(由于使用嵌套对象来存储向量)
  • 因为嵌套对象是单独的 Lucene 文档,所以嵌套对象是单独评分的,默认情况下,父文档被分配匹配嵌套文档的平均分数。您可以指定嵌套属性score_mode来更改评分行为。对于您的情况,“max”将根据描述最相似文档的最大余弦相似度得分进行评分。
  • 如果您有兴趣查看每个嵌套向量的分数,可以使用嵌套属性inner_hits
  • 如果有人好奇为什么将 +1.0 添加到余弦相似度得分中,那是因为 Cos. Sim。计算值 [-1,1],但 ElasticSearch 不能有负分数。因此,分数被转换为 [0,2]。