JosephG
JosephG

Reputation: 3253

ArangoDB Query List for Strings

I am relatively new to ArangoDB, and after reading through the docs am trying to implement it for a new project.

I have a collection of documents, and in each document is a list, which contains a number of terms. I am using the java driver, and would like to query for documents whose list matches any of the elements in the list I have.

Example:

Document 1
{
    tokens["blue", "red", "green"]
}

Document 2
{
    tokens["black", "red", "yellow"]
}

myArrayList:
["purple", "red"]

Since the ArrayList I am trying to query using contains the word "red", I should be presented with both document 1 and document 2. Ideally, I will only be presented with the document ID and the color that matches.

In half-psuedocode from what I know of AQL:

FOR document IN documents FILTER document.tokens CONTAINS myArrayList RETURN document.token.color && document._id

I normally have been returning the whole document object and then just accessing whatever I need. I could do that if it is easier. Eg:

FOR document IN documents FILTER document.tokens CONTAINS myArrayList RETURN document

Upvotes: 2

Views: 685

Answers (3)

CodeManX
CodeManX

Reputation: 11865

If you want to find documents, which at least contain all specified colors, in any order, you can use a query like this:

LET lenArrayList = LENGTH(@myArrayList)

FOR doc IN documents
    FILTER HAS(doc, "tokens") // avoid bad calls to INTERSECTION()
    FILTER LENGTH(INTERSECTION(@myArrayList, doc.tokens)) == lenArrayList
    RETURN doc

myArrayList: ["yellow","red"]

Result: document 2, because it contains red and yellow.

Upvotes: 0

JosephG
JosephG

Reputation: 3253

I have found an answer to my question on the ArangoDB Google Group. I am linking to it as it was very difficult for me to locate a solution: https://groups.google.com/forum/#!newtopic/arangodb/arangodb/fen4Nr7N4Uo

I have adapted the code there to work for my case: (Credit to stj's comment for fixing what I wrote)

FOR document IN documents LET contains = 
(FOR color IN document.tokens FILTER MATCHES(color, @myArrayList) RETURN color)
FILTER LENGTH(contains) > 0 RETURN document

Upvotes: 1

stj
stj

Reputation: 9097

I suggest using the IN operator for filtering as follows:

FOR document IN documents
  FILTER document.tokens IN @myArrayList
  RETURN document

This will only return a document if the tokens attribute is an array and contains any of the values contained in the @myArrayList bind parameter.

Upvotes: 4

Related Questions