linkyndy
linkyndy

Reputation: 17900

How can I filter documents that don't have a list of keys?

Say I have a table with documents having keys like:

name, created_at, [likes_to_eat], [likes_to_drink]

The keys between brackets are optional (may or may not be in the document).

I would like to fetch all documents from this table that don't have likes_to_eat and likes_to_drink keys. I've found in the docs that I could do this:

r.table('users').filter(
    lambda user: not user.has_fields('likes_to_eat', 'likes_to_drink')
).run(conn)

But has_fields puts an AND between the keys, whilst I need an OR (so filter a user whether he hasn't got likes_to_eat OR likes_to_drink OR both).

How can I do this?

Upvotes: 1

Views: 79

Answers (2)

neumino
neumino

Reputation: 4353

r.table('users').filter(
    lambda user: ~user.has_fields('likes_to_eat', 'likes_to_drink')
).run(conn)

Edit: Made a mistake and used contains intead of has_fields.

Upvotes: 2

linkyndy
linkyndy

Reputation: 17900

Seems that I was closer than I thought. I was negating using not instead of ~ (like @neumino suggested). So here's the working snippet:

r.table('users').filter(
    lambda user: ~user.has_fields('likes_to_eat', 'likes_to_drink')
).run(conn)

has_fields actually puts an OR between the given arguments.

Upvotes: 1

Related Questions