summaryrefslogtreecommitdiffstats
path: root/config-model/src/main/java/com/yahoo/searchdefinition/document/HnswIndexParams.java
blob: 70d0df8be7f092fe50d9c3f79eef1cd14fa5d8a7 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
// Copyright 2020 Oath Inc. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.searchdefinition.document;

import java.util.OptionalInt;

/**
 * Configuration parameters for a hnsw index used together with a 1-dimensional indexed tensor for approximate nearest neighbor search.
 *
 * @author geirst
 */
public class HnswIndexParams {

    public static final int DEFAULT_MAX_LINKS_PER_NODE = 16;
    public static final int DEFAULT_NEIGHBORS_TO_EXPLORE_AT_INSERT = 200;

    private final OptionalInt maxLinksPerNode;
    private final OptionalInt neighborsToExploreAtInsert;

    public static class Builder {
        private OptionalInt maxLinksPerNode = OptionalInt.empty();
        private OptionalInt neighborsToExploreAtInsert = OptionalInt.empty();

        public void setMaxLinksPerNode(int value) {
            maxLinksPerNode = OptionalInt.of(value);
        }
        public void setNeighborsToExploreAtInsert(int value) {
            neighborsToExploreAtInsert = OptionalInt.of(value);
        }
        public HnswIndexParams build() {
            return new HnswIndexParams(maxLinksPerNode, neighborsToExploreAtInsert);
        }
    }

    public HnswIndexParams() {
        this.maxLinksPerNode = OptionalInt.empty();
        this.neighborsToExploreAtInsert = OptionalInt.empty();
    }

    public HnswIndexParams(OptionalInt maxLinksPerNode, OptionalInt neighborsToExploreAtInsert) {
        this.maxLinksPerNode = maxLinksPerNode;
        this.neighborsToExploreAtInsert = neighborsToExploreAtInsert;
    }

    /**
     * Creates a new instance where values from the given parameter instance are used where they are present,
     * otherwise we use values from this.
     */
    public HnswIndexParams overrideFrom(HnswIndexParams rhs) {
        return new HnswIndexParams(rhs.maxLinksPerNode.isPresent() ? rhs.maxLinksPerNode : maxLinksPerNode,
                rhs.neighborsToExploreAtInsert.isPresent() ? rhs.neighborsToExploreAtInsert : neighborsToExploreAtInsert);
    }

    public int maxLinksPerNode() {
        return maxLinksPerNode.orElse(DEFAULT_MAX_LINKS_PER_NODE);
    }

    public int neighborsToExploreAtInsert() {
        return neighborsToExploreAtInsert.orElse(DEFAULT_NEIGHBORS_TO_EXPLORE_AT_INSERT);
    }
}