# Node Similarity and KNN

[Wiki](../README.md) / [Graph data science](README.md)

Use an existing [projection](projections.md#graph-catalogue); KNN property names must have been projected or added by mutate.

Node Similarity compares outgoing neighbour sets using `JACCARD`, `OVERLAP` or
`COSINE`. KNN compares property values: scalar numbers use
`1/(1+abs(a-b))`; integer lists default to Jaccard; floating lists default to
normalised cosine. Integer lists also support `OVERLAP`, and floating lists
support `EUCLIDEAN` and normalised `PEARSON`. Multiple property scores are
averaged. Property configuration accepts strings and metric maps:

```cypher
CALL gds.knn.stream('people', {
  nodeProperties: [{embedding: 'COSINE'}], topK: 10, similarityCutoff: 0.8
}) YIELD node1, node2, similarity;
```

KNN prepares numeric vectors and integer sets once. It uses sampled neighbour
descent: start with uniformly sampled neighbours, refine using forward and
bounded reverse neighbour lists, and add random candidates each iteration.
Defaults are `sampleRate:0.5`, `maxIterations:100`, `deltaThreshold:0.001`,
`randomJoins:10`. The first two fractions must be in `(0,1]`; iterations must be
positive and random joins non-negative. Set `randomSeed` for reproducibility.
`nodeProperties` also accepts a single property name. Similarity cutoff is
applied after neighbour refinement so it cannot block candidate exploration.

The GDB extension `exact:true` performs exhaustive comparisons. Graphs with at
most 64 selected nodes, or K covering every other node, automatically use exact
search. Stats report `exact`, `nodePairsConsidered`, `ranIterations` and
`didConverge`; convergence means neighbour updates met the stopping threshold,
not guaranteed exact neighbours. Approximate results may change from the older
exact-only implementation; use `exact:true` when exact results are required.
Ties prefer the lower node ID. RNG sequences are implementation-specific;
random-walk initial sampling and a perturbation option are not supported.

Node Similarity remains exact but retains at most K neighbours per source
while comparing pairs, giving O(N*K) retained candidates instead of O(N^2).
KNN also retains O(N*K) neighbour state, plus prepared property data and a
per-node candidate set. For positive similarity cutoffs and more than 64 selected
nodes, Node Similarity can enumerate only pairs sharing a neighbour. A cheap
join-work estimate selects this path on sparse graphs; dense/hub-heavy graphs
and zero-cutoff queries retain exhaustive comparison. Exact scores, zero-score
behaviour and node-ID tie ordering are preserved. Worst-case comparison work
remains quadratic.

## Related articles

[Graph projections and catalogue](projections.md) · [GDS algorithms and execution modes](algorithms.md) · [GDS resources and cancellation](resources.md) · [Graph data science](README.md)
