How to use MongoRegex (MongoDB C# Driver) - mongodb

Has anyone have any idea how to use MongoRegex for the document search?
I attempted this, but returns nothing back:
var spec = new Document();
spec.Add("Name", new MongoRegex("/" + searchKey + "*/", "i"));
collection.Find(spec)
Wondering why it doesn't work, I tried to execute following command from the console:
db.things.find({"Name":/john*/i}) /* WORKS */
db.things.find({"Name":"/john*/i"}) /* DOESN'T WORK */
Is that possible that the driver applies double quotation to the regex?
Thanks..

you just want a simple prefix query. Your regex is then ^ + searchKey. Also, this form will allow mongodb to use an index on Name.
var spec = new Document("Name", new MongoRegex(string.Format("^{0}",searchKey), "i"));
collection.Find(spec)

I think you need to not include the "/"s in C#, i.e.,
spec.Add("Name", new MongoRegex(searchKey + "*", "i"));

After digging the source code, I finally found the answer :)
var spec = new Document();
spec.Add("Name", new MongoRegex(".*" + searchKey + ".*", "i"));
collection.Find(spec)

Related

Angular2 Like request MongoDB

I want to do a pretty simple thing, a function that does a query to mongoDB using a Like. But I don't seem to make it works.
At the moment it looks like this :
searchChannel(valueToSearch:string){
this.items = Channels.find({'title':'/' + valueToSearch + '/'});
}
I tried /valueToSearch/ too, but it doesn't return any result.
To construct a regular expression from string you can use RegExp
searchChannel(valueToSearch:string){
this.items = Channels.find({'title': new RegExp(valueToSearch)});
}
Ok so... the issue is likely because you're inserting / characters into your mongo query. I think you want something like this:
searchChannel(valueToSearch:string){
this.items = Channels.find({'title': valueToSearch });
}
Unless the / characters are part of your stored content, they shouldn't be added to your search string.

Lucene Duplicated results / spaces in text search

I’m actually using Lucene 2.9.4.1 and everything works just fine if I search for something that exists just once in the same line.
Per instance, if Lucene find the same string that I’m looking for in the same line, I have duplicated (or more) results.
I’m actually using the following BooleanQuery:
booleanQuery.Add(new TermQuery(new Term(propertyInfo.Name, textSearch)), BooleanClause.Occur.SHOULD);
The second issue is about searching by something with spaces like “hello world”: never works.
Can anyone advise me or help me with these two malfunctioning features, please?
Thank you so much in advance,
Best regards,
Well, I just found the answer that solved both of my issues =)
I was using this:
BooleanQuery booleanQuery = new BooleanQuery();
PropertyInfo[] propertyInfos = typeof(T).GetProperties();
foreach (PropertyInfo propertyInfo in propertyInfos)
{
booleanQuery.Add(new TermQuery(new Term(propertyInfo.Name, textSearch)), BooleanClause.Occur.SHOULD);
}
And now I use this:
var booleanQuery = new BooleanQuery();
textSearch = QueryParser.Escape(textSearch.Trim().ToLower());
string[] properties = typeof(T).GetProperties().Select(x => x.Name).ToArray();
Analyzer analyzer = new StandardAnalyzer(global::Lucene.Net.Util.Version.LUCENE_29);
MultiFieldQueryParser titleParser = new MultiFieldQueryParser(Lucene.Net.Util.Version.LUCENE_29, properties, analyzer);
Query titleQuery = titleParser.Parse(textSearch);
booleanQuery.Add(titleQuery, BooleanClause.Occur.SHOULD);
It seems that Analyzer and MultiFieldQueryParser are the solution for my problems: no more duplicated results, I can search by something with spaces and … the performance as significantly raised up (faster results) =)

Why are definitions missing ? Lucene.Net 3.0.3 - Fast Vector Highlighter

As a newbie to Lucene.Net/Lucene and to C# I was able to put some lines of code and have a search running.
Now I want to get a snippet of the found area back. I have found below code but Visual Studio keeps telling me that a) "Searcher does contain a definition of getIndexReader" and b) "ScoreDoc does not contain a definition of doc" -and I don't get the point where the problem is!
Is there anybody out there who can help.
I am using Lucene.Net 3.0.3 and Lucene Contrib 3.0.3 on Visual Studio 2010 Express.
See the code I have below.
Thanks for your help!
RC
IndexReader indexReader = IndexReader.Open(directory, true);
Searcher indexSearch = new IndexSearcher(indexReader);
var queryParser = new QueryParser(Version.LUCENE_30, "text", analyzer);
var query = queryParser.Parse("\"system AKZ\"~10");
Console.WriteLine("Searching for: " + query);
TopDocs hits = indexSearch.Search(query,500);
/// Highlighter
FastVectorHighlighter fvHighlighter = new FastVectorHighlighter(true, true);
for (int i = 0; i < hits.ScoreDocs.Length; i++)
{
string bestfragment fvHighlighter.GetBestFragment(fvHighlighter.GetFieldQuery(query),indexSearch.getIndexReader(), hits.ScoreDocs[i].doc, "text", 20);
MessageBox.Show(bestfragment);
}
Console.WriteLine("Results Found: " + hits.TotalHits);
I would pull out something like ILSpy to examine what methods actually are available.
This is just a problem with the case of the method names. It's GetIndexReader() for example not getIndexReader(). You are probably basing this on docs for the Java implementation.
in Lucene.net this method's name is IndexReader.

Remove the last "," from the string list without the help of Substring and str.Length - 1 (C#3.0)

Consider the below code snippet
string src = "ibm,tcs";
string dest = src.Split(',').Select(i => i + "();,").ToArray().Aggregate((s, i) => s + i);
dest = dest.Substring(0, dest.Length - 1);
What I am doing is that, the Source string(src here) will have the string list in comma separated way.
The final output will be: ibm();,tcs();
As we can make out that, my program is doing so.
But I am taking the help of dest.Substring(0, dest.Length - 1); for eliminating the last "," that I am building in the Select Extension method.
I don't like this approach of mine.
Is there any other beautiful / elegant way of doing so? I am sure that someone will definitely approach in a better way :)
Also I will be happy if I get a solution using Lambda & Extension Method.
I am using C# 3.0 and dot net framework 3.5
Thanks
Just use string.Join instead of Aggregate, and don't include the comma in the Select clause:
string dest = string.Join(",", src.Split(',')
.Select(i => i + "();")
.ToArray());
In .NET 4 you wouldn't even need the ToArray() call (as extra overloads have been added to string.Join).
Or, as a completely alternative approach:
string dest = src.Replace(",", "();,") + "();";
string dest = string.Join(",", src.Split(',').Select(i => i + "();").ToArray());
or
string dest = string.Join(",", Array.ConvertAll(src.Split(','), s => s + "();"));

How do I disable some entities based on a few properties in NHibernate Search?

Im still pretty new to NHibernate.Search so please bear with me if this is stupid question :)
Say, I have indexed some entities of type BlogPost, which has a property called IsDeleted. If IsDeleted is set to true, I don't want my queries to show this particular blogpost.
Is this possible? And if it is - How? :P
Thanks in advance
- cwap
// Using NHibernate.Linq:
var result = Session.Linq<BlogPost>().Where(post => !post.IsDeleted).ToList();
// Using HQL:
var hql = "from BlogPost bp where bp.IsDeleted == false";
var result = Session.CreateQuery(hql).List<BlogPost>();
// Using Criteria API:
var result = s.CreateCriteria(typeof(BlogPost))
.Add(Restrictions.Eq("IsDeleted", false));
.List<BlogPost>();
NHibernate.Linq
HQL: Hibernate Query Language
Found the solution myself. I added the [Field(Index.Tokenized, Store = Store.Yes)]-attribute to the IsDeleted property, and added this clause to any query inbound:
string q = "(" + userQuery + ") AND IsDeleted:False";
I knew it was something simple :)