Home > Back-end >  RavenDB can't perform search with AND operator on nodejs
RavenDB can't perform search with AND operator on nodejs

Time:02-22

How can I perform a search with 'AND' operator via RavenDB?

Based on the docs it's written that I need to add the operator enum ("AND" \ "OR") as the third parameter of the search function. https://ravendb.net/docs/article-page/4.0/nodejs/client-api/session/querying/how-to-use-search

From some reason the AND operator does not work and it gives me OR results by default.

Example:

Users collection:

users/1-A: {
    firstName: 'Joe',
    lastName: 'Allen'
}

users/2-A: {
    firstName: 'Joe',
    lastName: 'Biden'
}

The call to raven:

session.query({ collection: 'Users' })
.search('firstName', 'Joe', 'AND') // search with AND operator
.search('lastName', 'Biden')
.all()

The call above returns back both documents. What should be the appropriate syntax for that?

Thanks

CodePudding user response:

So I found a solution for node.js. The "AND" enum as a third parameter did not work for me (according to this page: https://ravendb.net/docs/article-page/4.0/nodejs/client-api/session/querying/how-to-use-search).

I foundo another page: https://ravendb.net/docs/article-page/4.0/nodejs/indexes/querying/searching

Which uses andAlso() function on the query to use the "AND" operator and it works.

Example:

const joeBiden = session.query({ collection: 'Users' })
.search('firstName', 'Joe')
.andAlso()
.search('lastName', 'Biden')
.all()

This will return only Joe Biden's document.

Please note that it returns a promise.

** Raven will raise an error if you call the andAlso function and no query after it, so if you loop through possible search terms remember to exclude the andAlso function in the last search.

const joeBiden = session.query({ collection: 'Users' })
    .search('firstName', 'Joe')
    .andAlso()
    .search('lastName', 'Biden')
    .andAlso() // this line will cause Raven to throw an error
    .all()

CodePudding user response:

You can find detailed examples & walkthrough explanations in the following RavenDB demos:

https://demo.ravendb.net/demos/csharp/text-search/fts-query-search-basics https://demo.ravendb.net/demos/csharp/text-search/fts-query-search-operators

So this here above is currently only for C# client (nodeJS demos are TBD)

When using 2 separate search methods:
Then the other answer here - about using andAlso - is correct

When using single search method:
Using AND/OR is relevant only when you have 2 or more terms within the same search method.

i.e.:
.search('firstName', 'John Doe', 'AND')
will AND both terms (John && Doe)

.search('firstName', 'John Doe', 'OR')
will OR the results (John || Doe)

  • Related