Skip to content

Commit

Permalink
id 0 reserver
Browse files Browse the repository at this point in the history
  • Loading branch information
Oscar Franzen committed Mar 16, 2017
1 parent 0907554 commit 4b5ebe9
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 7 deletions.
11 changes: 7 additions & 4 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,9 @@ go-hnsw is a GO implementation of the HNSW approximate nearest-neighbour search

## Usage

Simple usage example. Note that both index building and searching can be safely done in parallel with multiple goroutines.
Simple usage example. See examples folder for more.
Note that both index building and searching can be safely done in parallel with multiple goroutines.
You can always extend the index, even while searching.

```go
package main
Expand All @@ -31,10 +33,11 @@ func main() {
h := hnsw.New(M, efConstruction, &zero)
h.Grow(10000)

for i := 0; i < 10000; i++ {
// Note that added ID:s must start from 1
for i := 1; i <= 10000; i++ {
h.Add(randomPoint(), uint32(i))
if (i+1)%1000 == 0 {
fmt.Printf("%v points added\n", i+1)
if (i)%1000 == 0 {
fmt.Printf("%v points added\n", i)
}
}

Expand Down
9 changes: 6 additions & 3 deletions hnsw.go
Original file line number Diff line number Diff line change
Expand Up @@ -256,15 +256,19 @@ func (h *Hnsw) Grow(size int) {

func (h *Hnsw) Add(q *Point, id uint32) {

if id == 0 {
panic("Id 0 is reserved, use ID:s starting from 1 when building index")
}

// generate random level
curlevel := int(math.Floor(-math.Log(rand.Float64() * h.LevelMult)))

epID := h.enterpoint
currentMaxLayer := h.nodes[epID].level
ep := &distqueue.Item{ID: h.enterpoint, D: DistFast(h.nodes[h.enterpoint].p, q)}

// Preassigned id (starting from 0), assume Grow has been called in advance
newID := uint32(id + 1)
// assume Grow has been called in advance
newID := id
newNode := node{p: q, level: curlevel, friends: make([][]uint32, min(curlevel, currentMaxLayer)+1)}

// first pass, find another ep if curlevel < maxLayer
Expand Down Expand Up @@ -419,7 +423,6 @@ func (h *Hnsw) Search(q *Point, ef int, K int) *distqueue.DistQueueClosestLast {
for resultSet.Len() > K {
resultSet.Pop()
}
// actually we should fix the id since our returned ids start from 1
return resultSet
}

Expand Down

0 comments on commit 4b5ebe9

Please sign in to comment.