简体   繁体   中英

How to perform a full text search in MongoDb with C# Lambda expression

There are a lot of answers how to get full-text search using Mongodb Driver Builders. But it has another way of ORM is lambdaexpressions to filter query.

var collection = _mongoContextFactory.GetCollection<Foo>();
collection.FindSync(x => x.Created >= new DateTime());

So How I will can to get full-text search using lambda ( I use specification pattern that provides expression interface)

Ok, I tried to find solution inside ExpressionFilterDefinition ( MongodbDriver converts lambda expression to this filter) and was defeated.

So, directly full text search is not supported by lambda expression. I switched on my imagination and created workaround for this task. I made abstract class for dto entity that utilize Full-Text index

  public abstract class FullTextSearchEntity
    {
        [BsonElement("$text"), BsonIgnoreIfNull]
        public FullTextSearchOption FullTextSearch { get; set; }
    }

As You can guess FullTextSearchOption repeats BSON structure for utilize fulltext index

  public class FullTextSearchOption
    {
        [BsonElement("$search"), BsonIgnoreIfNull]
        private string Search { get; set; }

        public FullTextSearchOption(string search)
        {
            Search = search;
        }
    }

And finally I added specification for usage this workaround:

  public class FullTextSearchSpecification<T> : SpecificationBase<T> where T: FullTextSearchEntity
    {
        private readonly string _searchQuery;

        public FullTextSearchSpecification(string searchQuery)
        {
            _searchQuery= searchQuery;
        }

        public override Expression<Func<T, bool>> ToExpression()
        {
            return entity=> entity.FullTextSearch == new FullTextSearchOption(_searchQuery);
        }
    }

Bingo!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM