Using regular Expressions with Mongodb - java

I am using Java Spring to work with Mongodb. I need to find documents which the word 'manager' is existed in description field. I tried following two method
Method 1
Query query = new Query();
query.addCriteria(Criteria.where("discription").regex("/\bmanager\b/"));
Method 2
Query query = new Query();
Pattern p = Pattern.compile("/\bmanager\b/");
query.addCriteria(Criteria.where("discription").regex(p));
But none of these were worked. I tried it with mongodb console like this
db.test.find({discription: {$regex: /\bmanager\b/}})
It worked as I expected. What's wrong with my Java code.

You don't have to add the slashes in the regex expression, as the regex method takes care of it. So
Query query = new Query();
query.addCriteria(Criteria.where("description").regex("\bmanager\b"));
should work.

It looks like you can just pass your regex string straight through without using Pattern.compile(). Have you tried that?

Related

Elasticsearch multiMatchQuery with wildcard

I have a requirement to search in all the fileds data with wild card in java using elaticsearch spring data in spring boot
Here is my code
String queryString = "362*";
final Query searchQuery = new NativeSearchQueryBuilder().withFilter(QueryBuilders.multiMatchQuery(queryString))
.build();
SearchHits<Measurement> meas = elasticsearchTemplate.search(searchQuery, Measurement.class);
System.out.println(meas.getTotalHits());
i am not able to get results with wildcard.
can someone help here.
multi-match queries is the multi field version of the match query. And like this one, it does not support wildcards but works on analysed text. See the documentation at https://www.elastic.co/guide/en/elasticsearch/reference/7.13/query-dsl-multi-match-query.html and https://www.elastic.co/guide/en/elasticsearch/reference/7.13/query-dsl-match-query.html

is there way to use multiprefix using elasticsearch java api?

using QueryBuilders.prefixQuery i'm trying to get the list of book title that starts with "L" or "J" is there any way to achieve that?
I know that QueryBuilders.prefixQuery can accept only string like boolQueryBuilder.must(QueryBuilders.prefixQuery("bookTitle", "L")); is there any othere simple way to achieve that?
you can use the boolean clause should and combine two prefix query one for L and one for J which will provide your expected search results, means books with starts from either L or J.
In java code it will look below:
BoolQueryBuilder boolQueryBuilder = new BoolQueryBuilder();
PrefixQueryBuilder lPrefixQueryBuilder = new PrefixQueryBuilder("title","L");
PrefixQueryBuilder jPrefixQueryBuilder = new PrefixQueryBuilder("title","J");
boolQueryBuilder.should(lPrefixQueryBuilder);
boolQueryBuilder.should(jPrefixQueryBuilder);

MongoDB Text Index using Java Driver

Using the MongoDB Java API, I have not been able to successfully locate a full example using text search. The code I am using is this:
DBCollection coll;
String searchString = "Test String";
coll.createIndex(new BasicDBObject ("blogcomments", "text"));
DBObject q = start("blogcomments").text(searchString).get();
The name of my collection that I am performing the search on is blogcomments. creatIndex() is the replacement method for the deprecated method ensureIndex(). I have seen examples for how to use the createIndex(), but not how to execute actual searches with the Java API. Is this the correct way to go about doing this?
That's not quite right. Queries that use indexes of type "text" can not specify a field name at query time. Instead, the field names to include in the index are specified at index creation time. See the documentation for examples. Your query will look like this:
DBObject q = QueryBuilder.start().text(searchString).get();

How to query mongodb with “like” using the java api without using Pattern Matching?

Currently I am using java to connect to MONGODB,
I want to write this sql query in mongodb using java driver:
select * from tableA where name like("%ab%")
is their any solution to perform the same task through java,
the query in mongodb is very simple i know, the query is
db.collection.find({name:/ab/})
but how to perform same task in java
Current I am using pattern matching to perform the task and code is
DBObject A = QueryBuilder.start("name").is(Pattern.compile("ab",
Pattern.CASE_INSENSITIVE)).get();
but it makes query very slow I think , does a solution exist that does not use pattern matching?
Can use Regular Expressions. Take a look at the following:
http://www.mongodb.org/display/DOCS/Advanced+Queries#AdvancedQueries-RegularExpressions
Make sure you understand the potential performance impacts!
DBObject A = QueryBuilder.start("name").is(Pattern.compile("ab",
Pattern.CASE_INSENSITIVE)).get();
I think this is one of the possible solution, you need to create index to achieve those.
Why do you fear the regular expressions? Once the expression is compiled they are very fast, and if the expression is "ab" the result is similar to a function that search a substring in a string.
However to do what you need you have 2 possibilities:
The first one, using regular expression, as you mention in your question. And I believe this is the best solution.
The second one, using the $where queries.
With $where queries you can specify expression like these
db.foo.find({"$where" : "this.x + this.y == 10"})
db.foo.find({"$where" : "function() { return this.x + this.y == 10; }"})
and so you can use the JavaScript .indexOf() on string fields.
Code snippet using the $regex clause (as mentioned by mikeycgto)
String searchString = "ab";
DBCollection coll = db.getCollection("yourCollection");
query.put("name",
new BasicDBObject("$regex", String.format(".*((?i)%s).*", searchString)) );
DBCursor cur = coll.find(query);
while (cur.hasNext()) {
DBObject dbObj = cur.next();
// your code to read the DBObject ..
}
As long as you are not opening and closing the connection per method call, the query should be fast.

how to query mongodb using the $ne operator?

i'm trying to do a $ne query in mongodb while using a regex, but it doesn't seem to work. the $ne (not equal) operator works fine when i don't use a regex though.
BasicDBObject q = new BasicDBObject()
q.put(field, ["\$ne": value])
the above works fine, the result set doesn't contain any documents that has that value for that field.
but i need it to be case insensitive. so i did this
q.put(field, ["\$ne": Pattern.compile(value, Pattern.CASE_INSENSITIVE)])
but this doesn't work..
so i thought, let me go to the command line and see if i can do it manually. so i did this:
db.Order.find({"bill.recipient.name": {$ne: /diep/i}},{"bill.recipient.name":1})
and it still doesn't work!
any ideas?
Try using $not instead of $ne.
http://www.mongodb.org/display/DOCS/Advanced+Queries#AdvancedQueries-Metaoperator%3A%24not
You can construct your query this way also
BasicDBObject query = new BasicDBObject();
query.append(fieldname,new BasicDBObject("$ne", value));

Categories

Resources