Dense vector field type

edit

The dense_vector field type stores dense vectors of numeric values. Dense vector fields are primarily used for k-nearest neighbor (kNN) search.

The dense_vector type does not support aggregations or sorting.

You add a dense_vector field as an array of numeric values based on element_type with float by default:

response = client.indices.create(
  index: 'my-index',
  body: {
    mappings: {
      properties: {
        my_vector: {
          type: 'dense_vector',
          dims: 3
        },
        my_text: {
          type: 'keyword'
        }
      }
    }
  }
)
puts response

response = client.index(
  index: 'my-index',
  id: 1,
  body: {
    my_text: 'text1',
    my_vector: [
      0.5,
      10,
      6
    ]
  }
)
puts response

response = client.index(
  index: 'my-index',
  id: 2,
  body: {
    my_text: 'text2',
    my_vector: [
      -0.5,
      10,
      10
    ]
  }
)
puts response
PUT my-index
{
  "mappings": {
    "properties": {
      "my_vector": {
        "type": "dense_vector",
        "dims": 3
      },
      "my_text" : {
        "type" : "keyword"
      }
    }
  }
}

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

PUT my-index/_doc/2
{
  "my_text" : "text2",
  "my_vector" : [-0.5, 10, 10]
}

Unlike most other data types, dense vectors are always single-valued. It is not possible to store multiple values in one dense_vector field.

Index vectors for kNN search

edit

A k-nearest neighbor (kNN) search finds the k nearest vectors to a query vector, as measured by a similarity metric.

Dense vector fields can be used to rank documents in script_score queries. This lets you perform a brute-force kNN search by scanning all documents and ranking them by similarity.

In many cases, a brute-force kNN search is not efficient enough. For this reason, the dense_vector type supports indexing vectors into a specialized data structure to support fast kNN retrieval through the knn option in the search API

Unmapped array fields of float elements with size between 128 and 4096 are dynamically mapped as dense_vector with a default similariy of cosine. You can override the default similarity by explicitly mapping the field as dense_vector with the desired similarity.

Indexing is enabled by default for dense vector fields and indexed as int8_hnsw. When indexing is enabled, you can define the vector similarity to use in kNN search:

response = client.indices.create(
  index: 'my-index-2',
  body: {
    mappings: {
      properties: {
        my_vector: {
          type: 'dense_vector',
          dims: 3,
          similarity: 'dot_product'
        }
      }
    }
  }
)
puts response
PUT my-index-2
{
  "mappings": {
    "properties": {
      "my_vector": {
        "type": "dense_vector",
        "dims": 3,
        "similarity": "dot_product"
      }
    }
  }
}

Indexing vectors for approximate kNN search is an expensive process. It can take substantial time to ingest documents that contain vector fields with index enabled. See k-nearest neighbor (kNN) search to learn more about the memory requirements.

You can disable indexing by setting the index parameter to false:

response = client.indices.create(
  index: 'my-index-2',
  body: {
    mappings: {
      properties: {
        my_vector: {
          type: 'dense_vector',
          dims: 3,
          index: false
        }
      }
    }
  }
)
puts response
PUT my-index-2
{
  "mappings": {
    "properties": {
      "my_vector": {
        "type": "dense_vector",
        "dims": 3,
        "index": false
      }
    }
  }
}

Elasticsearch uses the HNSW algorithm to support efficient kNN search. Like most kNN algorithms, HNSW is an approximate method that sacrifices result accuracy for improved speed.

Automatically quantize vectors for kNN search

edit

The dense_vector type supports quantization to reduce the memory footprint required when searching float vectors. Currently the only quantization method supported is int8 and provided vectors element_type must be float. To use a quantized index, you can set your index type to int8_hnsw. When indexing float vectors, the current default index type is int8_hnsw.

When using the int8_hnsw index, each of the float vectors' dimensions are quantized to 1-byte integers. This can reduce the memory footprint by as much as 75% at the cost of some accuracy. However, the disk usage can increase by 25% due to the overhead of storing the quantized and raw vectors.

response = client.indices.create(
  index: 'my-byte-quantized-index',
  body: {
    mappings: {
      properties: {
        my_vector: {
          type: 'dense_vector',
          dims: 3,
          index: true,
          index_options: {
            type: 'int8_hnsw'
          }
        }
      }
    }
  }
)
puts response
PUT my-byte-quantized-index
{
  "mappings": {
    "properties": {
      "my_vector": {
        "type": "dense_vector",
        "dims": 3,
        "index": true,
        "index_options": {
          "type": "int8_hnsw"
        }
      }
    }
  }
}

Parameters for dense vector fields

edit

The following mapping parameters are accepted:

element_type
(Optional, string) The data type used to encode vectors. The supported data types are float (default) and byte. float indexes a 4-byte floating-point value per dimension. byte indexes a 1-byte integer value per dimension. Using byte can result in a substantially smaller index size with the trade off of lower precision. Vectors using byte require dimensions with integer values between -128 to 127, inclusive for both indexing and searching.
dims
(Optional, integer) Number of vector dimensions. Can’t exceed 4096. If dims is not specified, it will be set to the length of the first vector added to the field.
index
(Optional, Boolean) If true, you can search this field using the kNN search API. Defaults to true.
similarity

(Optional*, string) The vector similarity metric to use in kNN search. Documents are ranked by their vector field’s similarity to the query vector. The _score of each document will be derived from the similarity, in a way that ensures scores are positive and that a larger score corresponds to a higher ranking. Defaults to cosine.

* This parameter can only be specified when index is true.

Valid values for similarity
l2_norm
Computes similarity based on the L2 distance (also known as Euclidean distance) between the vectors. The document _score is computed as 1 / (1 + l2_norm(query, vector)^2).
dot_product

Computes the dot product of two unit vectors. This option provides an optimized way to perform cosine similarity. The constraints and computed score are defined by element_type.

When element_type is float, all vectors must be unit length, including both document and query vectors. The document _score is computed as (1 + dot_product(query, vector)) / 2.

When element_type is byte, all vectors must have the same length including both document and query vectors or results will be inaccurate. The document _score is computed as 0.5 + (dot_product(query, vector) / (32768 * dims)) where dims is the number of dimensions per vector.

cosine
Computes the cosine similarity. During indexing Elasticsearch automatically normalizes vectors with cosine similarity to unit length. This allows to internally use dot_product for computing similarity, which is more efficient. Original un-normalized vectors can be still accessed through scripts. The document _score is computed as (1 + cosine(query, vector)) / 2. The cosine similarity does not allow vectors with zero magnitude, since cosine is not defined in this case.
max_inner_product
Computes the maximum inner product of two vectors. This is similar to dot_product, but doesn’t require vectors to be normalized. This means that each vector’s magnitude can significantly effect the score. The document _score is adjusted to prevent negative values. For max_inner_product values < 0, the _score is 1 / (1 + -1 * max_inner_product(query, vector)). For non-negative max_inner_product results the _score is calculated max_inner_product(query, vector) + 1.

Although they are conceptually related, the similarity parameter is different from text field similarity and accepts a distinct set of options.

index_options

(Optional*, object) An optional section that configures the kNN indexing algorithm. The HNSW algorithm has two internal parameters that influence how the data structure is built. These can be adjusted to improve the accuracy of results, at the expense of slower indexing speed.

* This parameter can only be specified when index is true.

Properties of index_options
type

(Required, string) The type of kNN algorithm to use. Can be either any of:

  • hnsw - This utilizes the HNSW algorithm for scalable approximate kNN search. This supports all element_type values.
  • int8_hnsw - The default index type for float vectors. This utilizes the HNSW algorithm in addition to automatically scalar quantization for scalable approximate kNN search with element_type of float. This can reduce the memory footprint by 4x at the cost of some accuracy. See Automatically quantize vectors for kNN search.
  • flat - This utilizes a brute-force search algorithm for exact kNN search. This supports all element_type values.
  • int8_flat - This utilizes a brute-force search algorithm in addition to automatically scalar quantization. Only supports element_type of float.
m
(Optional, integer) The number of neighbors each node will be connected to in the HNSW graph. Defaults to 16. Only applicable to hnsw and int8_hnsw index types.
ef_construction
(Optional, integer) The number of candidates to track while assembling the list of nearest neighbors for each new node. Defaults to 100. Only applicable to hnsw and int8_hnsw index types.
confidence_interval
(Optional, float) Only applicable to int8_hnsw and int8_flat index types. The confidence interval to use when quantizing the vectors, can be any value between and including 0.90 and 1.0. This value restricts the values used when calculating the quantization thresholds. For example, a value of 0.95 will only use the middle 95% of the values when calculating the quantization thresholds (e.g. the highest and lowest 2.5% of values will be ignored). Defaults to 1/(dims + 1).

Synthetic _source

edit

Synthetic _source is Generally Available only for TSDB indices (indices that have index.mode set to time_series). For other indices synthetic _source is in technical preview. Features in technical preview may be changed or removed in a future release. Elastic will work to fix any issues, but features in technical preview are not subject to the support SLA of official GA features.

dense_vector fields support synthetic _source .