If we know a document's link ID, we can invoke the FindByID method to look up the indexed document. The implementation is pretty straightforward; we just acquire a read lock and lookup for the specified ID in the internal map maintained by the indexer. If a matching entry exists, we create a copy and return it to the caller:
func (i *InMemoryBleveIndexer) FindByID(linkID uuid.UUID) (*index.Document, error) { return i.findByID(linkID.String()) } func (i *InMemoryBleveIndexer) findByID(linkID string) (*index.Document, error) { i.mu.RLock() defer i.mu.RUnlock() if d, found := i.docs[linkID]; found { return copyDoc(d), nil } return nil, xerrors.Errorf("find by ID: %w", index.ErrNotFound) }
You may be wondering why the FindByID implementation converts the input UUID into a string and delegates the actual document look up to the unexported findByID method. In the previous section, we saw that when we request bleve to index a document, we need to provide a string-based ID for the document. Bleve will return that ID to us when the document is matched by a search query. As will become evident in the following section, by providing a findByID method that accepts the linkID as a string, we can reuse the document lookup code when iterating search results.
To update the PageRank score for an existing document, clients invoke the UpdateScore method, which expects a document's link ID and the updated PageRank score:
func (i *InMemoryBleveIndexer) UpdateScore(linkID uuid.UUID, score float64) error { i.mu.Lock() defer i.mu.Unlock() key := linkID.String() doc, found := i.docs[key] if !found { doc = &index.Document{LinkID: linkID} i.docs[key] = doc } doc.PageRank = score if err := i.idx.Index(key, makeBleveDoc(doc)); err != nil { return xerrors.Errorf("update score: %w", err) } return nil }
Updating any searchable document attribute requires a reindex operation. Consequently, the UpdateScore implementation will acquire a write lock and look up the document in the internal document map. If the document is found, its PageRank score will be updated in-place and the document will be passed to bleve for indexing.