keymap.go 1.7 KB
Newer Older
tavit ohanian's avatar
tavit ohanian committed
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 61 62 63 64 65 66 67 68 69 70 71
package coreindex

import (
	"fmt"
	"path"
	"strconv"
	"strings"

	ds "gitlab.dms3.io/dms3/go-datastore"
)

//
// index keystore conventions
//	 reposet key convention
// 	   - <index>/reposet/<kind>/<type>-<name>
//
const rootPrefix = "/index/reposet"

//
// 	 corpus key convention
// 	  - <index>/reposet/<kind>/<type>-<name>/<repo-index-in-set>/corpus
//
const corpusDocPrefix = "/corpus"

// GetRepoSetKey - return a datastore key for a reposet
func GetRepoSetKey(t, k, n string) (ds.Key, error) {
	key := ds.NewKey(path.Join(rootPrefix, k, t, "-", n))
	return key, nil
}

// DecomposeRepoSetKey - decompose a giver datastore key to constituent parts
func DecomposeRepoSetKey(k string) (rtype, rkind, rname string, err error) {
	// verify key length
	key := ds.NewKey(k)
	kl := key.List()
	if len(kl) < 4 {
		err = fmt.Errorf("invalid reposet key length %v", key)
		return
	}
	// verify key prefix
	rootKey := ds.NewKey(rootPrefix)
	rl := rootKey.List()
	for i := range rl {
		if rl[i] != kl[i] {
			err = fmt.Errorf("invalid reposet key prefix %v", key)
			return
		}
	}
	// extract and return reposet class and name
	switch len(kl) {
	case 4:
		rtype = ""
		rkind = kl[len(rl)+1]
		rname = kl[len(rl)+2]
		sep := strings.Index(rname, "-")
		if sep > 0 {
			rtype = rname[0 : sep-1]
			rname = rname[sep:rname[len(rname)]]
		}
	default:
		err = fmt.Errorf("invalid reposet key length %v", key)
	}
	return
}

// GetDocKey - return a datastore key for a corpus document
func GetDocKey(rc string, rn string, ri int64, di int64) (ds.Key, error) {
	// Key: rootPrefix + "/_class_/_name_/_n_/corpus/_i_"
	key := ds.NewKey(path.Join(rootPrefix, rc, rn, strconv.FormatInt(ri, 10), corpusDocPrefix, strconv.FormatInt(di, 10)))
	return key, nil
}