ostafen / clover

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

Add a Contains criteria #44

Closed ostafen closed 2 years ago

ostafen commented 2 years ago

Hi, all! It could be useful to implement a Contains(elems ...interface{}) to check if a slice field contains one or more elements. For example, assume to run the following query

db.Query("myCollection").Where(c.Field("myField").Contains(4)) 

on a `myCollection" collection which consists of the following three documents:

{
   ...,
   "myField": [1,2,4]
},
{
   ...,
   "myField": [5,6,7]
},
{
   ...,
   "myField": [4, 10, 20]
}

The query would return only the first and the third document.

kastolars commented 2 years ago

Hi! I'd like to give this a shot. Just for clarification, what field types (elems) should this function support? I see int in the example and interface in the signature.

ostafen commented 2 years ago

Hi, thank you for your interest :=) The signature of every criteria usually accepts interface{}, so that different types can be supported. Give a look, for example, at the In criteria, which is very similar to this one (it accepts a []interface). You can use reflect.DeepEqual() to perform comparison of interface{} values

kastolars commented 2 years ago

In the Contains function, can I assume the docValue in docValue := doc.Get(f.name) (similar to the In function) is of type slice, or maybe should it panic in the instance where it isn't a slice? Or maybe fall back to using the In function? What do you think?

ostafen commented 2 years ago

You should use a type assertion to first check if it is a slice. In the case the field is not a slice, the criteria in not satisfied and you can return false. A criteria should never panic, but rather return false in such scenarios