Vector KNN search

Updated at:

The Lindorm graph engine can store vectors as vertex properties and use the approximate nearest neighbor (ANN) search capability provided by the vector engine to find vertices most similar to a query vector in Gremlin queries. This capability is suitable for scenarios such as semantic retrieval, similar content recommendation, and expanding vector recall results through graph relationships. This topic uses document retrieval as an example to describe vector search scoring and how to use hasVector to perform KNN (K-Nearest Neighbor) search on vertices.

Prerequisites

  • Lindorm Graph Engine is activated and the access whitelist is configured.

  • Lindorm Vector Engine is activated.

  • The HTTP endpoint, database name, username, and password of Graph Engine are obtained.

Vector search scoring

Note

For detailed information and calculation methods, see the relevant Vector Engine documentation: Appendix: Calculation method of vector search scores (_score).

The graph engine calculates scores based on the distance returned by the vector engine:

score = 1 / (1 + distance)

The distance and score ranges for L2 and COSINE are as follows.

Distance type

Distance definition

Distance range

_score range

L2

sum((query[i] - vector[i])²), i.e., squared Euclidean distance

[0, +∞)

(0, 1]

COSINE

1 - cosineSimilarity(query, vector)

[0, 2]

[1/3, 1]

Typical scores are as follows:

Scenario

distance

_score

L2: Vectors are identical

0

1

L2: Squared distance is 1

1

0.5

L2: Squared distance is 4

4

0.2

COSINE: Same direction

0

1

COSINE: Orthogonal

1

0.5

COSINE: Opposite direction

2

1/3

Note the following when using scores:

  • The theoretical minimum score for COSINE is 1/3, not 0. If the cosine similarity of your business vectors falls within [0,1], the actual score range is [0.5,1].

  • The score for L2 can approach 0 arbitrarily closely.

  • Different distance types produce different score distributions. We recommend that you calibrate thresholds separately based on your business data rather than sharing the same threshold across distance types.

Perform KNN search on vertices

Vector search on vertices typically includes the following steps:

  1. Use hasVector to recall vertices most similar to the query vector.

  2. Optionally return similarity scores, filter out low-relevance results, or continue with graph traversal.

hasVector KNN search syntax

hasVector provides the following two call forms:

hasVector(vectorProperty, queryVector, topK)
hasVector(vectorProperty, queryVector, topK, searchParams)

The following table describes the parameters.

Parameter

Required

Description

vectorProperty

Yes

The name of the vertex property for which a vector index is defined.

queryVector

Yes

The query vector. The array elements must be numeric values, and the dimension must match the property definition.

topK

Yes

The maximum number of results to recall from the vector index. Must be greater than 0.

searchParams

No

A search parameter map, such as min_score, with_score, and index search parameters.

hasVector must be used immediately after a hasLabel step that specifies exactly one vertex label. For example, the following query returns the IDs of the 4 vertices in document that are closest to [1,0,0,0]:

g.V().hasLabel('document')
  .hasVector('embedding', [1.0d, 0.0d, 0.0d, 0.0d], 4)
  .id()

The corresponding curl request is as follows:

curl -sS -u "$GRAPH_AUTH" -X POST \
  "$GRAPH_ENDPOINT/gremlin/$GRAPH_DB" \
  -H 'Content-Type: application/json' \
  -H 'Accept: application/json' \
  --data '{
    "gremlin": "g.V().hasLabel(\"document\").hasVector(\"embedding\",[1.0d,0.0d,0.0d,0.0d],4).id()"
  }'

A possible response for the sample data is as follows:

{
  "requestId": "<request-id>",
  "status": {
    "message": "",
    "code": 200,
    "attributes": {
      "@type": "g:Map",
      "@value": []
    }
  },
  "result": {
    "data": {
      "@type": "g:List",
      "@value": [
        "doc_same",
        "doc_scaled",
        "doc_orthogonal",
        "doc_opposite"
      ]
    },
    "meta": {
      "@type": "g:Map",
      "@value": []
    }
  }
}

The business results are in result.data["@value"]. The preceding example returns doc_same, doc_scaled, doc_orthogonal, and doc_opposite in order. Results are returned in descending order of _score.

Common hasVector KNN search patterns

Return vertices and their business properties

Use valueMap(true) to return the vertex ID, label, and all properties:

g.V().hasLabel('document')
  .hasVector('embedding', [1.0d, 0.0d, 0.0d, 0.0d], 1)
  .valueMap(true)

By default, with_score is not enabled, so the results do not include _score.

If you only need specific business properties, you can specify the property names explicitly:

g.V().hasLabel('document')
  .hasVector('embedding', [1.0d, 0.0d, 0.0d, 0.0d], 4)
  .valueMap('title', 'category')

Return similarity scores

Set with_score=true in the fourth parameter:

g.V().hasLabel('document')
  .hasVector(
    'embedding',
    [1.0d, 0.0d, 0.0d, 0.0d],
    4,
    {"with_score": true}
  )
  .valueMap('title', 'category', '_score')

The following shows the logical results after unwrapping the GraphSON type wrappers:

[
  {"title":["Exact match"],"category":["guide"],"_score":[1.0]},
  {"title":["Same direction different length"],"category":["guide"],"_score":[0.5]},
  {"title":["Orthogonal vector"],"category":["reference"],"_score":[0.33333334]},
  {"title":["Opposite vector"],"category":["archive"],"_score":[0.2]}
]

In GraphSON, _score is returned as a multi-valued vertex property, so in the valueMap() result it is typically a list containing a single floating-point number. Clients need to parse it as a list.

If you only need a list of score values, you can use:

g.V().hasLabel('document')
  .hasVector(
    'embedding',
    [1.0d, 0.0d, 0.0d, 0.0d],
    4,
    {"with_score": true}
  )
  .values('_score')
  .fold()

Filter low-relevance results with min_score

min_score sets the minimum relevance score. The following query first recalls up to 100 vertices from the vector index, then retains only results with a score of at least 0.8:

g.V().hasLabel('document')
  .hasVector(
    'embedding',
    [1.0d, 0.0d, 0.0d, 0.0d],
    100,
    {"min_score": 0.8, "with_score": true}
  )
  .valueMap('title', '_score')

The conversion between min_score and maximum distance is as follows:

maxDistance = 1 / min_score - 1

For L2 and COSINE, we recommend setting min_score within (0,1]. A value of 0 means virtually no distance filtering is applied. A value greater than 1 will not match any results for these two distance types. For COSINE, a threshold no greater than 1/3 theoretically cannot filter out any valid non-zero vectors.

Adjust index search parameters

searchParams supports the following parameters.

Parameter

Valid range

Description

min_score

>= 0

The minimum relevance score.

with_score

Boolean

Whether to return _score. Default value: false.

ef_search

Integer [1,1000]

The candidate width for HNSW search.

nprobe

Integer [1,1000000]

The number of cluster centers to probe during IVF search.

reorder_factor

Float [0,200]

Expands the candidate set and re-ranks results based on the original vectors.

Parameters should match the index type. For example, HNSW indexes primarily use ef_search, IVF indexes primarily use nprobe, and quantized indexes can use reorder_factor. The graph engine validates and passes through these parameters, but does not guarantee that parameters mismatched with the current index type will affect recall results. Unknown parameters cause query errors.

The following example expands the vector recall range, sets a minimum score, and returns the top 20 results:

g.V().hasLabel('document')
  .hasVector(
    'embedding',
    [1.0d, 0.0d, 0.0d, 0.0d],
    100,
    {
      "min_score": 0.75,
      "with_score": true,
      "ef_search": 100,
      "reorder_factor": 10
    }
  )
  .limit(20)
  .valueMap('title', '_score')

Continue filtering or traversing after vector recall

You can continue to use standard Gremlin steps after hasVector. For example, the following query filters the vector recall results to include only vertices with a status of online:

g.V().hasLabel('document')
  .hasVector(
    'embedding',
    [1.0d, 0.0d, 0.0d, 0.0d],
    100,
    {"with_score": true}
  )
  .has('status', 'online')
  .limit(10)
  .valueMap('title', 'status', '_score')

topK limits the number of results recalled from the vector index. Subsequent filtering does not automatically replenish candidates. For example, if only 3 out of the 10 candidates from topK=10 satisfy status='online', the query returns at most 3 results. To return more results after filtering, increase topK and then use limit() to cap the final count.

Important

Property filtering steps must be placed after hasVector. hasVector serves as the starting step for vector search. Standard filtering steps placed before it are not included in the final query. Do not use the following pattern:

// Incorrect: the status filter does not take effect as expected
g.V().hasLabel('document')
  .has('status', 'online')
  .hasVector('embedding', [1.0d, 0.0d, 0.0d, 0.0d], 100)

Use parameter bindings

Query vectors and search parameters can be passed through bindings in the request to avoid concatenating long vectors in the Gremlin string:

curl -sS -u "$GRAPH_AUTH" -X POST \
  "$GRAPH_ENDPOINT/gremlin/$GRAPH_DB" \
  -H 'Content-Type: application/json' \
  -H 'Accept: application/json' \
  --data '{
    "gremlin": "g.V().hasLabel(\"document\").hasVector(\"embedding\",queryVector,100,params).limit(10).valueMap(\"title\",\"_score\")",
    "bindings": {
      "queryVector": [1.0, 0.0, 0.0, 0.0],
      "params": {
        "min_score": 0.8,
        "with_score": true,
        "ef_search": 100
      }
    }
  }'

Limits

  • hasVector is only used for KNN search on vertex vector properties.

  • hasVector must be preceded by exactly one hasLabel step. The label cannot be omitted, and multiple labels cannot be specified.

  • The topK value in hasVector must be greater than 0.

  • The query vector must be a numeric array, and its dimension must match the schema definition.

  • _score is a reserved property name. It exists only in queries where with_score=true is set, and cannot be modified or deleted.

  • with_score only accepts the Boolean values true and false or their string equivalents. Other values cause query errors.

  • Unknown searchParams parameters cause query errors.

  • Property filtering steps should be placed after hasVector. To ensure a specific number of results after filtering, increase topK and then use limit().