Query an array with an array of values


#1

I have data items like this:

{
mydata:
[
{
title: "item 1",
languages: ["en", "fr", "it", "pl"]
},
{
title: "item 2",
languages: ["fr", "es", "pt"]
},
{
title: "item 3",
languages: ["en", "it"]
}
]
}

How can I query for items in an array like [“en”, “it”]? It should match all data elements that contain either “en”, “it” or both in languages?

Thank you very much for your help.


#2

You can use the ANY operator to test whether any item in an array meets a condition. In this case you’d need two of those, one to look for each string.


#3

The Problem is, that the number of languages in the database may have up to 25 entries. Also the number of items to query for is variable. It may be only 1 or it may be 15. How to put that into code?

I tried this:
var valueExpressions: [ExpressionProtocol] = [ExpressionProtocol]()
for lang in languages {
valueExpressions.append(Expression.string(lang))
}

But it does not work.


#4

The solution must be something like this:

.select(SelectResult.expression(Meta.id)) .from(DataSource.database(db)) .where(ArrayFunction.contains(Expression.property("languages"), value: Expression.string("en"))) .or(Expression.propertyArrayFunction.contains(Expression.property("languages"), value: Expression.string("it")))

But how can I have an arbitrary number of “or” clauses?