ostafen / clover

A lightweight document-oriented NoSQL database written in pure Golang.
MIT License
633 stars 54 forks source link

Question: Is there a way to search for a value in all fields? #110

Closed jcsco closed 1 year ago

jcsco commented 1 year ago

I'm trying to evaluate if this DB serves my purpose. I have a use case where I need to search for a value in all the fields. Something like below:

db.FindAll(c.NewQuery("todos").Where(c.AnyField.Eq("seach string")))

I got my test code working by collecting all the fields from the document and dynamically building the criteria string:

    for field := range fieldSet {
        criteria = criteria.Or(clover.Field(field).Eq(value))
    }

Wondering if there is a better way to search through all documents?

ostafen commented 1 year ago

I think you can use the MatchFunc method of the query object which simply accepts a function taking a document and returns a bool. It is the quickest way to build custom criteria

jcsco commented 1 year ago

@ostafen Thanks for your response. Your suggestion worked and it's pretty fast compared to the other approach.

    docs, err := ces.db.FindAll(clover.NewQuery(collection).MatchFunc(func(doc *clover.Document) bool {
        for _, v := range doc.ToMap() {
            val, ok := v.(string)
            if !ok {
                continue
            }

            if val == value {
                return true
            }
        }
        return false
    }).Sort(clover.SortOption{Field: "eventTimestamp", Direction: 1}))