google-code-export / morphia

Automatically exported from code.google.com/p/morphia
1 stars 0 forks source link

The hasAnyOf method of the FieldEnd class is not working properly with regular expressions #369

Closed GoogleCodeExporter closed 9 years ago

GoogleCodeExporter commented 9 years ago
Let's say you want to query mongodb via the command-line shell with a regular 
expression, in order to make sql-like query ("like" keyword and "%" operator) :
{ "keywords" : { "$in" : [/.*firstKeyword.*/, /.*secondKeyword.*/]}} 

This works fine. 
Now in the morphia version you can do this :
query.field("keywords").hasAnyOf(keywordsList); 

When executed, the generated mongodb query is :
{ "keywords" : { "$in" : [ "/.*firstKeyword.*/", "/.*secondKeyword.*/"]}} 

The problem here is that morphia adds double quotes for each keyword. As a 
result, regular expressions are not detected by mongodb.

Versions :
Morphia version : 0.99
Mongo driver version : 2.7.2

Original issue reported on code.google.com by loupasch...@gmail.com on 30 Jan 2012 at 10:37

GoogleCodeExporter commented 9 years ago
*Precisions*
The keywordsList is initialized like that :

List<String> keywordsList = new ArrayList<String>(); 
keywordsList.add("/.*firstKeyword.*/"); 
keywordsList.add("/.*secondKeyword.*/"); 
query.field("keywords").hasAnyOf(keywordsList); 

Original comment by loupasch...@gmail.com on 12 Feb 2012 at 9:47

GoogleCodeExporter commented 9 years ago
Strings are not regular expressions, and won't be treated like them on
the server.

Please use Patter.compile(String) instead of those strings.
http://docs.oracle.com/javase/1.4.2/docs/api/java/util/regex/Pattern.html#compil
e(java.lang.String)

Original comment by scotthernandez on 13 Feb 2012 at 12:26

GoogleCodeExporter commented 9 years ago
Thanks for your advice, you're right, it works !

Here's the new code I use :

List<Pattern> keywordsList = new ArrayList<Pattern>(); 
keywordsList.add(Pattern.compile(".*firstKeyword.*")); 
keywordsList.add(Pattern.compile(".*secondKeyword.*")); 
query.field("keywords").hasAnyOf(keywordsList); 

Original comment by loupasch...@gmail.com on 13 Feb 2012 at 6:42