Select Git revision
document_store.go
-
Jan Semmelink authoredJan Semmelink authored
document_store.go 9.12 KiB
package search
import (
"bytes"
"context"
"encoding/json"
"io/ioutil"
"net/http"
"reflect"
"strings"
opensearchapi "github.com/opensearch-project/opensearch-go/opensearchapi"
"gitlab.com/uafrica/go-utils/errors"
"gitlab.com/uafrica/go-utils/logger"
"gitlab.com/uafrica/go-utils/reflection"
)
type DocumentStore interface {
Write(id string, data interface{}) error
Search(query Query, limit int64) (ids []string, totalCount int, err error)
Get(id string) (doc interface{}, err error)
Delete(id string) error
}
type documentStore struct {
w *writer
name string
dataType reflect.Type
settings Settings
mappings Mappings
jsonSettings []byte
jsonMappings []byte
created bool
searchResponseBodyType reflect.Type
getResponseBodyType reflect.Type
}
//purpose:
// create a document store index to write e.g. orders then allow one to search them
//parameters:
// name must be the complete openSearch index name e.g. "uafrica-v3-orders"
// tmpl must be your document data struct consisting of public fields as:
// Xxx string `json:"<name>" search:"keyword|text|long|date"` (can later add more types)
// Xxx time.Time `json:"<name>"` assumes type "date" for opensearch
// Xxx int `json:"<name>"` assumes type "long" for opensearch, specify keyword if required
func (w *writer) DocumentStore(name string, tmpl interface{}) (DocumentStore, error) {
if !indexNameRegex.MatchString(name) {
return nil, errors.Errorf("invalid index_name:\"%s\"", name)
}
//if already created, just return
if existingDocumentStore, ok := w.documentStoreByName[name]; ok {
return existingDocumentStore, nil
}
structType := reflect.TypeOf(tmpl)
if tmpl == nil || structType.Kind() != reflect.Struct {
return nil, errors.Errorf("%T is not a struct", tmpl)
}
ds := &documentStore{
w: w,
name: name,
dataType: structType,
created: false,
}
//define the OpenSearch index mapping
ds.settings = Settings{
Index: &SettingsIndex{