<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Captain Codeman&#187; nhibernate</title>
	<atom:link href="http://www.captaincodeman.com/tag/nhibernate/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.captaincodeman.com</link>
	<description>Software Developer</description>
	<lastBuildDate>Fri, 15 Jul 2011 22:50:00 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.1.4</generator>
		<item>
		<title>Pattern for efficiently paging database rows on a web page</title>
		<link>http://www.captaincodeman.com/2010/06/06/pattern-efficiently-paging-database-rows-web-page/</link>
		<comments>http://www.captaincodeman.com/2010/06/06/pattern-efficiently-paging-database-rows-web-page/#comments</comments>
		<pubDate>Sun, 06 Jun 2010 16:57:34 +0000</pubDate>
		<dc:creator>Captain Codeman</dc:creator>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[MVC]]></category>
		<category><![CDATA[action]]></category>
		<category><![CDATA[controller]]></category>
		<category><![CDATA[jquery]]></category>
		<category><![CDATA[json]]></category>
		<category><![CDATA[mongodb]]></category>
		<category><![CDATA[nhibernate]]></category>
		<category><![CDATA[paging]]></category>

		<guid isPermaLink="false">http://www.captaincodeman.com/?p=200</guid>
		<description><![CDATA[The technique I use for paging through database rows which I’ve found works efficiently and is easy to re-use. It works well for both traditional and AJAX requests and handles sorting and filtering requirements as well. This is based on ASP.NET MVC, jQuery and NHibernate + SQL Server but the principals will be the same for other technologies.


No related posts.]]></description>
			<content:encoded><![CDATA[<p>It shouldn’t be difficult to read rows from a database and render them on a web page – it’s a pretty fundamental operation that most web apps have to do but a surprising number don’t get quite right, especially when the volume of data grows and it can’t all be loaded and rendered within a single request. I’ve recently come across several ‘enterprise applications’ that simply fail to get it right – one extreme example loaded <em><strong>all</strong></em> the database rows into session state and then used LINQ to get and display the pages from that (!) and another took the approach of simply not paging the results at all which meant huge pages that were incredibly slow to load and as the data grew beyond the simple developer-test dataset.</p>
<p>So, I’m going to try and explain the technique I use for paging through rows which I’ve found works efficiently and is easy to re-use. It works well for both traditional and AJAX requests and handles sorting and filtering requirements as well. This is based on ASP.NET MVC, jQuery and NHibernate + SQL Server but the principals will be the same for other technologies (I’ve used the same basic approach with MongoDB as the back-end data-store).</p>
<h2>Paged Data Model</h2>
<p>We’ll start by defining a generic abstract class that will make it easy for us to re-use the approach for different lists. This will represent the ‘set’ of data on a page together with some additional information about the position of the page within the entire list, the total number of records and the sort order applied etc…</p>
<pre class="brush:csharp">/// &lt;summary&gt;
/// Represents a paged list of data.
/// &lt;/summary&gt;
/// &lt;typeparam name="T"&gt;The item type in the list&lt;/typeparam&gt;
/// &lt;typeparam name="TS"&gt;The sort order specifier type.&lt;/typeparam&gt;
public abstract class PagedList&lt;T, TS&gt;
{
    /// &lt;summary&gt;
    /// Gets or sets the list of entities.
    /// &lt;/summary&gt;
    public IEnumerable&lt;T&gt; List { get; set; }

    /// &lt;summary&gt;
    /// Gets or sets the current page number.
    /// &lt;/summary&gt;
    public int PageNo { get; set; }

    /// &lt;summary&gt;
    /// Gets or sets the number of records per page.
    /// &lt;/summary&gt;
    public int PageSize { get; set; }

    /// &lt;summary&gt;
    /// Gets or sets the total number of records.
    /// &lt;/summary&gt;
    public int RecordCount { get; set; }

    /// &lt;summary&gt;
    /// Gets or sets the first record number displayed.
    /// &lt;/summary&gt;
    public int StartRecord { get; set; }

    /// &lt;summary&gt;
    /// Gets or sets a value indicating whether this &lt;see cref="PagedList&lt;T, TS&gt;"/&gt; is the latest page.
    /// &lt;/summary&gt;
    /// &lt;value&gt;&lt;c&gt;true&lt;/c&gt; if latest; otherwise, &lt;c&gt;false&lt;/c&gt;.&lt;/value&gt;
    public bool Latest { get; set; }

    /// &lt;summary&gt;
    /// Gets or sets SortSeq.
    /// &lt;/summary&gt;
    public TS SortSeq { get; set; }
}</pre>
<p>The &lt;T&gt; and &lt;TS&gt; generic property types represent the type of entry that will be in the list (the ‘things’ we are paging over) and an Enum representing the sort-order required. As an example, we’ll page over a set of UserSummary entities and the sort-order will be defined with a UserSortSequence Enum:</p>
<pre class="brush:csharp">/// &lt;summary&gt;
/// How users are ordered in result sets
/// &lt;/summary&gt;
public enum UserSortSequence
{
    /// &lt;summary&gt;
    /// Order by name alphabetically
    /// &lt;/summary&gt;
    ByName, 

    /// &lt;summary&gt;
    /// Order by date joined
    /// &lt;/summary&gt;
    ByJoined, 

    /// &lt;summary&gt;
    /// Order by number of topics started
    /// &lt;/summary&gt;
    ByTopics, 

    /// &lt;summary&gt;
    /// Order by number of posts
    /// &lt;/summary&gt;
    ByPosts, 

    /// &lt;summary&gt;
    /// Order by reputation
    /// &lt;/summary&gt;
    ByReputation
}</pre>
<p>The PagedList is abstract so we need to create a specific class to represent the type of paged set that we want to use and this class will also contain any additional filtering parameters that our paging system will use. In this case, we will create a UserSet class that contains an additional Name property for filtering.</p>
<pre class="brush:csharp">/// &lt;summary&gt;
/// Represents a user set.
/// &lt;/summary&gt;
public class UserSet : PagedList&lt;UserSummary, UserSortSequence&gt;
{
    /// &lt;summary&gt;
    /// Gets or sets Name to filter.
    /// &lt;/summary&gt;
    public string Name { get; set; }
}</pre>
<h2>Controller &amp; Action</h2>
<p>With these classes in place we can create a controller action to handle the request. A simplified version is shown below:</p>
<pre class="brush:csharp">/// &lt;summary&gt;
/// Display paged user set filtered and sorted as required.
/// &lt;/summary&gt;
/// &lt;param name="name"&gt;The name filter.&lt;/param&gt;
/// &lt;param name="page"&gt;The page number.&lt;/param&gt;
/// &lt;param name="size"&gt;The page size.&lt;/param&gt;
/// &lt;param name="sort"&gt;The sort sequence.&lt;/param&gt;
/// &lt;returns&gt;&lt;/returns&gt;
public ActionResult Index(string name, int page, int size, UserSortSequence sort)
{
    var model = new UserSet { PageNo = page, PageSize = size, SortSeq = sort, Name = name };
    this.Repository.PopulateUserSet(model);

    return View(model);
}</pre>
<h2>Data Access Layer</h2>
<p>The real work is done in the PopulateUserSet method of the repository. This needs to do 3 things:</p>
<ol>
<li>Get the total number of rows matching whatever filter criteria are specified.</li>
<li>Calculate the rows to display based on the page number and page size specified.</li>
<li>Get the set of data from the database applying any sort order specified.</li>
</ol>
<p>The sample below uses several NHibernate features and takes advantage of it’s ability to translate a paged-set request into the specific dialect of the database in question using whatever ROW_NUMBER functionality may be available so that the query operates as efficiently as possible.</p>
<pre class="brush:csharp">/// &lt;summary&gt;
/// Populate user set with paged data.
/// &lt;/summary&gt;
/// &lt;param name="userset"&gt;The user set.&lt;/param&gt;
public void PopulateUserSet(UserSet userset)
{
    // Get total count for all users in this set
    userset.RecordCount = this.session.CreateCriteria(typeof(Account))
        .Add(Restrictions.Like("Name", userset.Name, MatchMode.Anywhere))
        .SetProjection(Projections.RowCount())
        .UniqueResult&lt;int&gt;();

    // calculate the last page based on the record count and page size
    int lastPage = ((userset.RecordCount - 1) / userset.PageSize) + 1;

    // ensure page number is in range
    if (userset.PageNo &lt; 1) {
        userset.PageNo = 1;
    }
    else if (userset.PageNo &gt; lastPage) {
        userset.PageNo = lastPage;
        userset.Latest = true;
    }

    userset.StartRecord = (userset.PageNo - 1) * userset.PageSize;

    // create criteria to get user account with paging
    ICriteria userListCriteria = this.session.CreateCriteria(typeof(UserSummary))
        .Add(Restrictions.Like("Name", userset.Name, MatchMode.Anywhere))
        .SetFirstResult(userset.StartRecord)
        .SetMaxResults(userset.PageSize);

    // add ordering to criteria
    switch (userset.SortSeq)
    {
        case UserSortSequence.ByJoined:
            userListCriteria.AddOrder(Order.Asc("RegisteredOn"));
            break;
        case UserSortSequence.ByName:
            userListCriteria.AddOrder(Order.Asc("Name"));
            break;
        case UserSortSequence.ByPosts:
            userListCriteria.AddOrder(Order.Desc("PostCount"));
            break;
        case UserSortSequence.ByReputation:
            userListCriteria.AddOrder(Order.Desc("Reputation"));
            break;
        case UserSortSequence.ByTopics:
            userListCriteria.AddOrder(Order.Desc("TopicCount"));
            break;
    }

    // get the list of users
    userset.List = userListCriteria.List&lt;UserSummary&gt;();
}</pre>
<h2>View Rendering</h2>
<p>So, we have a representation of a paged set of data, the action to retrieve it and the repository method to populate it. We now need a way of displaying the data and providing links for the user to navigate around it. How the rows are rendered obviously depends on the requirements of your application.</p>
<pre class="brush:html"><%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<UserSet>" %>

<asp:Content ContentPlaceHolderID="content" runat="server">
<ul id="data" class="topics">
    <% foreach (UserSummary userSummary in Model.List) { %>
        <%= Html.DisplayFor(x => userSummary) %>
    <% } %>
    </ul>
<ul class="paging"></ul>

</asp:Content>

<asp:Content ContentPlaceHolderID="scripts" runat="server">
    <script type="text/javascript">
        $(function() {  
            setPaging('<%= Html.Encode(Model.Name) %>', <%= Model.PageNo %>, <%= Model.PageSize %>, <%= Model.RecordCount %>);	
        });

        function setPaging(name, page, pageSize, records) {
            $('.paging').paging({
                page: page,
                pageSize: pageSize,
                records: records,
                url: '<%= Url.RouteUrl("users", new { name = "***", page = 99999 }) %>'.replace('***', name).replace('99999', '#')
            });    
        }
    </script>
</asp:Content></pre>
<h2>Rendering Paged Links</h2>
<p>I’m using a jQuery plug-in to display the page links because it saves doing so much work on the server and it makes it easier to AJAX enable the UI. In the full implementation the controller action can return a full view or just the JSON data for the paged set and the UI uses a template to render it and update the page links.</p>
<p>The paging itself is rendered using a jQuery plug-in. This is designed to intelligently decide which links to render and whether to enable or disable the previous and next links. It keeps the first and last links always visible and ensures that a few links either side of the current page (which is highlighted) are rendered while avoiding silly gaps (like having 1, 2, … 4 instead of 1, 2, 3, 4). Also, the ‘…’ separators are also links to the midpoint of the non-displayed sequence to make it easier to quickly jump around even large lists.</p>
<p>Here is an example of a 10 page set of links rendering using the rules outlines above:</p>
<p><img style="display: inline; margin-left: 0px; margin-right: 0px; border-width: 0px;" title="page-links" src="http://www.captaincodeman.com/wp-content/uploads/2010/06/pagelinks.png" border="0" alt="page-links" width="300" height="331" /></p>
<p>The code to render this is below:</p>
<pre class="brush:javascript">/*
 * jQuery paging plugin
 *
 * http://www.captaincodeman.com/
 *
 */
(function($) {
    $.fn.paging = function(options) {

        // extend our default options with those provided.
        var settings = $.extend(true, {}, $.fn.paging.defaults, options);

        return this.each(function() {

            function render() {
                panel.empty();

                // calc pages, separators etc... to output
                var pageCount = Math.floor((settings.records - 1) / settings.pageSize) + 1;

                var pages = [];
                var pageStart, pageFinish;

                if (settings.inline) {
                    settings.prev = false;
                    settings.next = false;
                }

                var prevNextCount = 0;
                if (settings.prev) prevNextCount++;
                if (settings.next) prevNextCount++;

                if (settings.prev) {
                    if (currentPage &gt; 1) {
                        pages[pages.length] = new PageEntry(settings.prevText, currentPage - 1, PageType.Previous);
                    } else {
                        pages[pages.length] = new PageEntry(settings.prevText, currentPage, PageType.PreviousDisabled);
                    }
                }

                if (pageCount &lt;= settings.max + (settings.min * 2) + prevNextCount) {
                    // no separator required
                    addPages(pages, 1, pageCount);
                } else
                    if (currentPage &lt;= settings.max) {
                    // cluster at the start
                    addPages(pages, 1, Math.max(currentPage + 1, settings.max));
                    addSeparator(pages, Math.max(currentPage + 1, settings.max), pageCount - settings.min);
                    addPages(pages, pageCount - settings.min + 1, pageCount);
                } else
                    if (currentPage &gt;= pageCount - settings.max + 1) {
                    // cluster at the end
                    addPages(pages, 1, settings.min);
                    addSeparator(pages, settings.min, Math.min(currentPage - 1, pageCount - settings.max + 1));
                    addPages(pages, Math.min(currentPage - 1, pageCount - settings.max + 1), pageCount);
                } else {
                    // cluster in the middle
                    var offset = (settings.max - 1) / 2;
                    addPages(pages, 1, settings.min);
                    addSeparator(pages, settings.min, currentPage - offset);
                    addPages(pages, currentPage - offset, currentPage + offset);
                    addSeparator(pages, currentPage + offset, pageCount - settings.min + 1);
                    addPages(pages, pageCount - settings.min + 1, pageCount);
                }

                if (settings.next) {
                    if (currentPage &lt; pageCount) {
                        pages[pages.length] = new PageEntry(settings.nextText, currentPage + 1, PageType.Next);
                    } else {
                        pages[pages.length] = new PageEntry(settings.nextText, currentPage, PageType.NextDisabled);
                    }
                }

                // render pages
                for (var idx = 0; idx &lt; pages.length; idx++) {
                    if (settings.inline &#038;&#038; pages[idx].Page == 1) {
                    } else {

                        var clickHandler = function(page) {
                            return function(event) { return pageSelected(UrlFormat(page), page, event); }
                        }

                        var item;

                        switch (pages[idx].PageType) {
                            case PageType.Previous:
                            case PageType.Next:
                                item = $("&lt;a /&gt;")
                                    .bind("click", clickHandler(pages[idx].Page))
						            .attr("href", UrlFormat(pages[idx].Page))
						            .attr("class", 'prevnext')
						            .attr("title", "page " + pages[idx].Page)
						            .text(pages[idx].Text);
                                break;
                            case PageType.PreviousDisabled:
                            case PageType.NextDisabled:
                                item = $("&lt;span /&gt;")
						            .attr("class", 'prevnext')
						            .text(pages[idx].Text);
                                break;
                            case PageType.Separator:
                                item = $("&lt;a /&gt;")
                                    .bind("click", clickHandler(pages[idx].Page))
						            .attr("href", UrlFormat(pages[idx].Page))
						            .attr("class", 'sep')
						            .attr("title", "page " + pages[idx].Page)
						            .text(pages[idx].Text);
                                break;
                            case PageType.Page:
                                item = $("&lt;a /&gt;")
                                    .bind("click", clickHandler(pages[idx].Page))
						            .attr("href", UrlFormat(pages[idx].Page))
						            .attr("title", "page " + pages[idx].Page)
						            .text(pages[idx].Text);
                                break;
                            case PageType.PageSelected:
                                item = $("&lt;span /&gt;")
						            .attr("class", 'current')
						            .text(pages[idx].Text);
                                break;
                        }

                        panel.append(item);
                    }
                };
            }

            function pageSelected(url, page, event) {
                currentPage = page;
                var continuePropagation = settings.callback(url, page);
                if (!continuePropagation) {
                    if (event.stopPropagation) {
                        event.stopPropagation();
                    }
                    else {
                        event.cancelBubble = true;
                    }
                    render();
                }
                return continuePropagation;
            }

            function addPages(pages, start, finish) {
                for (var page = start; page &lt;= finish; page++) {
                    if (page == currentPage) {
                        pages[pages.length] = new PageEntry(page, page, PageType.PageSelected);
                    } else {
                        pages[pages.length] = new PageEntry(page, page, PageType.Page);
                    }
                }
            }

            function addSeparator(pages, start, finish) {
                var page = Math.ceil((finish - start) / 2) + start;
                pages[pages.length] = new PageEntry(settings.separatorText, page, PageType.Separator);
            }

            function UrlFormat(page) {
                return settings.url.replace("#", page);
            }

            var panel = jQuery(this);
            var currentPage = settings.page;
            render();
        });
    };

    var PageType = {
        Previous: 3,
        PreviousDisabled: 4,
        Next: 5,
        NextDisabled: 6,
        Separator: 7,
        Page: 8,
        PageSelected: 9
    }

    function PageEntry(text, page, pageType) {
        this.Text = text;
        this.Page = page;
        this.PageType = pageType;
    }

    $.fn.paging.defaults = {
        page: 1,
        pageSize: 20,
        records: 0,
        min: 1,
        max: 3,
        inline: false,
        prev: true,
        prevText: '« prev',
        next: true,
        nextText: 'next »',
        separator: true,
        separatorText: '...',
        url: '#',
        callback: function() { return true; }
    };

})(jQuery);</pre>
<h2>Summary</h2>
<p>These are all the pieces and hopefully it gives you an idea of how it all works. A full implementation will usually contain some extra pieces – besides the AJAX enabled rendering using JSON and client-side templates I’ll also have other links to enable to page-size to be adjusted and the sort-order changed and these are persisted to a cookie in the controller action using a custom binder. Hopefully though, what I’ve shown here will help you get a good solid and efficient paging system implemented.</p>
<p>Please let me know if any part of this is unclear or you’d like further details on any of the pieces.</p>


<p>No related posts.</p>]]></content:encoded>
			<wfw:commentRss>http://www.captaincodeman.com/2010/06/06/pattern-efficiently-paging-database-rows-web-page/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Benefits of NoSQL (MongoDb) for the Query-side of CQRS</title>
		<link>http://www.captaincodeman.com/2010/04/11/benefits-nosql-mongodb-query-cqrs/</link>
		<comments>http://www.captaincodeman.com/2010/04/11/benefits-nosql-mongodb-query-cqrs/#comments</comments>
		<pubDate>Mon, 12 Apr 2010 02:31:26 +0000</pubDate>
		<dc:creator>Captain Codeman</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[cqrs]]></category>
		<category><![CDATA[mongodb]]></category>
		<category><![CDATA[nhibernate]]></category>
		<category><![CDATA[nosql]]></category>

		<guid isPermaLink="false">http://www.captaincodeman.com/?p=158</guid>
		<description><![CDATA[As you may know I&#8217;ve been researching CQRS and the benefits of using this approach to developing systems. My focus at the moment is on the Query side of things and for this I&#8217;ve been comparing a SQL Server / NHibernate solution with a NoSQL alternative using MongoDb. For this, I&#8217;ve been using a simple forum


No related posts.]]></description>
			<content:encoded><![CDATA[<p>As you may know I&#8217;ve been researching CQRS and the benefits of using this approach to developing systems. My focus at the moment is on the Query side of things and for this I&#8217;ve been comparing a SQL Server / NHibernate solution with a NoSQL alternative using MongoDb. For this, I&#8217;ve been using a simple forum app that I&#8217;ve been working on with a database of around 4m posts and 200k topics.</p>
<p>I&#8217;ll post more detailed results when I have time to show things in more detail (with some example code) but basically, the performance difference I&#8217;ve been seeing is huge.</p>
<p>The SQL Server / NHibernate solution was generating about 10 requests per second and had SQL Server at about 50% of the CPU. The MongoDB backed solution was running at around 50 requests per second and MongoDb was sat at around 3-4% of CPU time.</p>
<p>Right now, I&#8217;m very excited about the possibilities of improving app performance (especially now that Google are taking this into account when calculating page-rank) but also, the difference in the complexity of the code between the two systems is also refreshing with the MongoDb solution very, very simple and quick to develop.</p>


<p>No related posts.</p>]]></content:encoded>
			<wfw:commentRss>http://www.captaincodeman.com/2010/04/11/benefits-nosql-mongodb-query-cqrs/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Homongous! MongoDB, NoSQL and CQRS</title>
		<link>http://www.captaincodeman.com/2010/03/31/homongous-mongodb-nosql-cqrs/</link>
		<comments>http://www.captaincodeman.com/2010/03/31/homongous-mongodb-nosql-cqrs/#comments</comments>
		<pubDate>Wed, 31 Mar 2010 17:11:55 +0000</pubDate>
		<dc:creator>Captain Codeman</dc:creator>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[MVC]]></category>
		<category><![CDATA[automapper]]></category>
		<category><![CDATA[cqrs]]></category>
		<category><![CDATA[cte]]></category>
		<category><![CDATA[fluentnhibernate]]></category>
		<category><![CDATA[json]]></category>
		<category><![CDATA[mongodb]]></category>
		<category><![CDATA[nhibernate]]></category>
		<category><![CDATA[ninject]]></category>
		<category><![CDATA[nosql]]></category>
		<category><![CDATA[object database]]></category>
		<category><![CDATA[rdbms]]></category>
		<category><![CDATA[SQL Server]]></category>

		<guid isPermaLink="false">http://www.captaincodeman.com/?p=131</guid>
		<description><![CDATA[I&#8217;ve got what I consider to be a pretty good development stack &#8211; all the usual suspects: MVC for the front-end; data stored in SQL Server or MySQL and accessed via NHibernate with mappings using FluentNHibernate conventions; the domain model mapped to a view model using AutoMapper and a sprinkling of NInject dependency injection to


No related posts.]]></description>
			<content:encoded><![CDATA[<p>I&#8217;ve got what I consider to be a pretty good development stack &#8211; all the usual suspects: <a href="http://www.asp.net/mvc/">MVC</a> for the front-end; data stored in <a href="http://www.microsoft.com/sqlserver/">SQL Server</a> or <a href="http://www.mysql.com/">MySQL</a> and accessed via <a href="http://nhforge.org/">NHibernate</a> with mappings using <a href="http://fluentnhibernate.org/">FluentNHibernate</a> conventions; the domain model mapped to a view model using <a href="http://automapper.codeplex.com/">AutoMapper</a> and a sprinkling of <a href="http://ninject.org/">NInject</a> dependency injection to tie it all together without direct dependencies.</p>
<p>And of course it works, it&#8217;s proven &#8211; lots of people use this approach. Lately though I&#8217;ve been reading a lot about different architectural approaches and in particular <a href="http://www.udidahan.com/2009/12/09/clarified-cqrs/">CQRS</a> or &#8216;<a href="http://elegantcode.com/2009/11/11/cqrs-la-greg-young/">Command Query Responsibility Segregation</a>&#8216; from <a href="http://www.udidahan.com/?blog=true">Udi Dahan</a> and <a href="http://codebetter.com/blogs/gregyoung/">Greg Young</a> which, among other things, promotes the idea of having a separate denormalized repository for querying data and another, possibly normalized relational database, for writing to.</p>
<p>Because the query-side repository is denormalized it really lends itself to using a <a href="http://en.wikipedia.org/wiki/NoSQL">NoSQL approach</a> which seems to be gaining ground so I thought I&#8217;d give it a try to see how well it would work using a forum app I&#8217;ve been re-developing (currently an MVC/NHibernate/SQL Server based app).</p>
<p>Now, it&#8217;s not facebook but it&#8217;s not trivial either &#8211; there are about 4m posts spread over 200k topics and I&#8217;ve done quite a bit of work on the database side of things to make sure it&#8217;s efficient and normalized. One feature I&#8217;m implementing is to go away from the old and boring topic list that most forums have (where they show the topic title, author, date, number of replies and sometimes the date and author of the latest reply) and present it more graphically with the avatar of the topic starter, the title, date and folder it&#8217;s in and then the avatars of the last 3 or more (depending on configuration) people who have replied. Here&#8217;s an example:</p>
<p><a rel="attachment wp-att-132" href="http://www.captaincodeman.com/2010/03/31/homongous-mongodb-nosql-cqrs/topic-summary/"><img class="alignnone size-full wp-image-132" title="topic-summary" src="http://www.captaincodeman.com/wp-content/uploads/2010/03/topic-summary.png" alt="" width="600" height="60" /></a></p>
<p>Now, to do this with the relational model means that I need to do quite a few table joins and when there are 4m+ rows that I need to be able to sort and page over it can start to chug a little. So, to speed things up I&#8217;ve spent some time optimizing the queries to use <a href="http://msdn.microsoft.com/en-us/library/cc917715.aspx">Indexed Views</a> to combine the Topic, Folder and Author and <a href="http://msdn.microsoft.com/en-us/library/ms190766.aspx">Common Table Expressions (CTE)</a> to get the last 3 replies which means joining the Topic, Post and Author tables again. It all works and it&#8217;s pretty quick but it&#8217;s been a lot of work to get it to that point.</p>
<p>So, the first test was to pick a NoSQL database to try as an alternative. I read up on quite a few and looked at the features and compatibility with Windows/C#/.NET including <a href="http://couchdb.apache.org/">CouchDB</a>, <a href="http://www.mongodb.org/">MongoDB</a>, <a href="http://cassandra.apache.org/">Cassandra</a>, <a href="http://project-voldemort.com/">Voldemort </a>and <a href="http://nosql-database.org/">others</a> and in the end decided to go with MongoDB.</p>
<p><a href="http://www.mongodb.org/display/DOCS/Quickstart">Downloading and installing MongoDB</a> (basically just unzipping the files) was easy and with the excellent documentation I was up and running really quickly and ready to start trying things out.</p>
<p>The first step was to try reading and writing documents using C# and this was really straightforward using the <a href="http://www.mongodb.org/display/DOCS/C+Sharp+Language+Center">mongodb-csharp driver</a>. So, next step was to convert the data from SQL Server into it. I already had the queries that created the paged views of data &#8211; typically with 10 or 20 records per page and thought I&#8217;d just re-use that. Running against the whole recordset really slowed it down though but after SQL Server chugged away for 10 or 15 minutes and used 6.5Gb of RAM it managed to give me the data and I created the <a href="http://www.json.org/">JSON</a> documents in-memory ready for inserting.</p>
<p>So, I call &#8216;Insert&#8217; to add the collection of documents to the MongoDB store. And it failed. Well, actually &#8230; I assumed it failed because it only seemed to take about 5 seconds and my console app finished. When I went to the MongoDB console and queried the data though it was all there &#8230; and I could query it, sort it, page through it, very VERY quickly &#8211; much quicker than using SQL Server and the relational model. Windows process explorer showed MongoDB used just a few Mb of RAM to do this.</p>
<p>Because querying was so easy and so direct I no longer needed to use an OR/M to address the <a href="http://en.wikipedia.org/wiki/Object-relational_impedance_mismatch">object-relational impedance mismatch</a> (a fancy way of saying an RDBMS sucks for OO) and I no longer needed to transform the persistent domain model into a view model before presenting it. I can just get the view model objects straight from the store and render them. Fast, simple, and I get to delete lots of code which is kind of soul destroying when you&#8217;ve written it but I&#8217;m excited at all the code I won&#8217;t have to write in future with this approach and the performance.</p>
<p>MongoDB is very, very fast and very easy to use although it requires a slightly different way of thinking when you&#8217;re more used to working with a relational model. One of the big selling points is that it&#8217;s easier to scale than a relational system and while I didn&#8217;t try the sharding support (which is in alpha) I did give the replication a go &#8211; again, it was much easier to setup than the equivalent would be with SQL Server and it performed very well.</p>
<p>Finally, I did a few more experiments to test the insert performance compared to SQL Server and basically setup a simple table with an Id, Name and Number column and inserted 500,000 rows. I used parameterized queries for SQL Server, re-used the same command object and wrapped it all in a single transaction but it took over 55 seconds to run (plus I had to create the database and table in advance which took a minute or two). Doing the same thing with MongoDB ran in under 10 seconds and the client code was much simpler and I didn&#8217;t have any initial setup.</p>
<p>I&#8217;m definitely going to explore MongoDB more and plan on making use of it in future projects when it&#8217;s appropriate. The next piece to look at is the Command side of CQRS where I want to use <a href="http://codebetter.com/blogs/gregyoung/archive/2010/02/20/why-use-event-sourcing.aspx">event sourcing for storage</a> and an event driven / service oriented architecture and better domain driven design techniques.</p>


<p>No related posts.</p>]]></content:encoded>
			<wfw:commentRss>http://www.captaincodeman.com/2010/03/31/homongous-mongodb-nosql-cqrs/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>NHibernate.Search using Lucene.NET Full Text Index (3)</title>
		<link>http://www.captaincodeman.com/2008/04/26/nhibernatesearch-using-lucene-net-full-text-index-part3/</link>
		<comments>http://www.captaincodeman.com/2008/04/26/nhibernatesearch-using-lucene-net-full-text-index-part3/#comments</comments>
		<pubDate>Sun, 27 Apr 2008 01:07:00 +0000</pubDate>
		<dc:creator>Captain Codeman</dc:creator>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[full text indexing]]></category>
		<category><![CDATA[index]]></category>
		<category><![CDATA[lucene]]></category>
		<category><![CDATA[MVC]]></category>
		<category><![CDATA[nhibernate]]></category>
		<category><![CDATA[search]]></category>

		<guid isPermaLink="false">http://blogs.intesoft.net/post.aspx?id=98ef581c-c67c-4d0a-bb7a-c63b4be74c83</guid>
		<description><![CDATA[In Part 1 we looked at how to create a full-text index of NHibernate persisted domain objects using the Lucene.NET project. Part 2 then looked at how to query the index complete with query-parsing and hit-highlighting of the results. Now that we have a full-text index there are other things that we can use it


No related posts.]]></description>
			<content:encoded><![CDATA[<p>In <a title="Creating a full-text index of NHibernate persisted objects" href="http://blogs.intesoft.net/post/2008/03/NHibernateSearch-using-Lucene-NET-Full-Text-Index-Part1.aspx">Part 1</a> we looked at how to create a full-text index of <a title="NHibernate" href="http://www.nhibernate.org/" target="_blank">NHibernate</a> persisted domain objects using the <a title="Lucene.NET" href="http://incubator.apache.org/lucene.net/" target="_blank">Lucene.NET</a> project. <a title="Querying the Lucene.NET index and displaying results" href="http://blogs.intesoft.net/post/2008/03/NHibernateSearch-using-Lucene-NET-Full-Text-Index-Part2.aspx">Part 2</a> then looked at how to query the index complete with query-parsing and hit-highlighting of the results.</p>
<p>Now that we have a full-text index there are other things that we can use it for. The easiest and most useful is probably adding a &#8216;similar items&#8217; feature where the system can automatically display related items based on the text that they share in common. While it isn&#8217;t exact the results are often surprisingly good and while a human editor could probably pick out some links with more finesse it can quickly become an impossible task as the number of items grow &#8211; the human will typically resort to searching for similar items using the index anyway so why not automate it?!</p>
<p>This feature can be used to display related web pages or blog entries or, in this case, related books. It probably isn&#8217;t too far off from the system that Amazon uses. The benefit is that as new content is being added, the top related items can constantly be updated &#8211; even for existing items in the system. So, for example, if a new Harry Potter book is released then the existing books can immediately start linking to it and vice-versa or if a company starts offering a new training course or product then any related pages will immediately start to link together.</p>
<p>While it sounds complicated, it is actually quite easy thanks to the contrib assemblies provided with <a title="Lucene.NET" href="http://incubator.apache.org/lucene.net/" target="_blank">Lucene.NET</a>. In fact, it&#8217;s so simple it&#8217;s almost trivial so this won&#8217;t be a long post!</p>
<p>First, we need to add a new reference to the SimilarityNet.dll assembly (part of Lucene.NET contrib). This provides a SimilarityQueries class which contains a FormSimilarQuery method. Calling this will a piece of text (from an existing field), an analyzer and the field name will produce a boolean query using every unique word where all words are optional. If we repeat this with each field, boosting the relevance of the most important ones (such as title) then we end up with a query that will look for every word in each field of the original item.</p>
<p>To quote the Lucene documentation:</p>
<blockquote><p>The philosophy behind this method is &#8220;two documents are similar if they share lots of words&#8221;. Note that behind the scenes, Lucene&#8217;s scoring algorithm will tend to give two documents a higher similarity score if the share more uncommon words.</p>
</blockquote>
<p>What this means in practice is that the more unique a word is, the more likely it will be taken into account when ranking the similar items. So, if our original book has &#8216;Agile&#8217; in the title and words such as &#8216;scrum&#8217; and &#8216;backlog&#8217; in the summary then chances are we will find other books that also have these more unique words &#8230; and it&#8217;s very likely that they will be related to our original book.</p>
<p>Of course, when we search our index for books with all these words there is going to be one obvious match &#8211; the original book! In fact, this should be the first result returned so we could either skip this when creating the result-set (looking for the same unique Id rather than just skipping the first one just to be safe) or, as in the example below, use a boolean search and specifically exclude the Id of the source item from the query. I haven&#8217;t experimented to see which one is quicker but I prefer to let Lucene do all the work &#8211; I trust it and it saves me writing any more code or getting results back that I am just going to discard which feels wrong.</p>
<p>Here is the code to find the best 4 similar matches to any book passed in. Note that I include the Authors and Publisher fields when doing the comparison so it will tend to favour books by the same author or publisher &#8211; you will need to experiment to see what makes most sense for your application and usage.</p>
<pre class="csharpcode"><span class="rem">/// &lt;summary&gt;</span>
<span class="rem">/// Gets similar books.</span>
<span class="rem">/// &lt;/summary&gt;</span>
<span class="rem">/// &lt;param name="book"&gt;The book.&lt;/param&gt;</span>
<span class="rem">/// &lt;returns&gt;&lt;/returns&gt;</span>
<span class="kwrd">public</span> <span class="kwrd">override</span> IList&lt;IBook&gt; GetSimilarBooks(IBook book)
{
    IFullTextSession session = (IFullTextSession)NHibernateHelper.GetCurrentSession();
    Analyzer analyzer = <span class="kwrd">new</span> StandardAnalyzer();
    BooleanQuery query = <span class="kwrd">new</span> BooleanQuery();

    Query title = Similarity.Net.SimilarityQueries.FormSimilarQuery(book.Title, analyzer, <span class="str">"Title"</span>, <span class="kwrd">null</span>);
    title.SetBoost(10);
    query.Add(title, BooleanClause.Occur.SHOULD);

    <span class="kwrd">if</span> (book.Summary != <span class="kwrd">null</span>) {
        Query summary =
            Similarity.Net.SimilarityQueries.FormSimilarQuery(book.Summary, analyzer, <span class="str">"Summary"</span>, <span class="kwrd">null</span>);
        summary.SetBoost(5);
        query.Add(summary, BooleanClause.Occur.SHOULD);
    }

    <span class="kwrd">if</span> (book.Authors != <span class="kwrd">null</span>) {
        Query authors =
            Similarity.Net.SimilarityQueries.FormSimilarQuery(book.Authors, analyzer, <span class="str">"Authors"</span>, <span class="kwrd">null</span>);
        query.Add(authors, BooleanClause.Occur.SHOULD);
    }

    <span class="kwrd">if</span> (book.Publisher != <span class="kwrd">null</span>) {
        Query publisher =
            Similarity.Net.SimilarityQueries.FormSimilarQuery(book.Publisher, analyzer, <span class="str">"Publisher"</span>, <span class="kwrd">null</span>);
        query.Add(publisher, BooleanClause.Occur.SHOULD);
    }
</pre>
<pre class="csharpcode">    <span class="rem">// avoid the book being similar to itself!</span>
    query.Add(<span class="kwrd">new</span> TermQuery(<span class="kwrd">new</span> Term(<span class="str">"Id"</span>, book.Id.ToString())), BooleanClause.Occur.MUST_NOT);

    IQuery nhQuery = session.CreateFullTextQuery(query, <span class="kwrd">new</span> Type[] { <span class="kwrd">typeof</span>(Book) })
                            .SetMaxResults(4);

    IList&lt;IBook&gt; books = nhQuery.List&lt;IBook&gt;();
    <span class="kwrd">return</span> books;
}
</pre>
<style type="text/css">.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}
.csharpcode .lnum { color: #606060; }
</style>
<p>&nbsp;</p>
<p>That about wraps it up for using NHibernate and Lucene. I&#8217;m expecting things to change when the new NHibernate version 2.0 is released so I&#8217;ll probably post again to update you of any changes though when it is. Also, there are a few other features available in Lucene which I may blog about such as using Synonyms for the &#8216;did you mean &#8230;&#8217; type suggestions.</p>
<p>Please let me know if there is anything that I haven&#8217;t explained particularly well or you would like to see more about.</p>


<p>No related posts.</p>]]></content:encoded>
			<wfw:commentRss>http://www.captaincodeman.com/2008/04/26/nhibernatesearch-using-lucene-net-full-text-index-part3/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>NHibernate.Search using Lucene.NET Full Text Index (2)</title>
		<link>http://www.captaincodeman.com/2008/03/30/nhibernatesearch-using-lucene-net-full-text-index-part2/</link>
		<comments>http://www.captaincodeman.com/2008/03/30/nhibernatesearch-using-lucene-net-full-text-index-part2/#comments</comments>
		<pubDate>Sun, 30 Mar 2008 22:16:36 +0000</pubDate>
		<dc:creator>Captain Codeman</dc:creator>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[full text indexing]]></category>
		<category><![CDATA[index]]></category>
		<category><![CDATA[lucene]]></category>
		<category><![CDATA[MVC]]></category>
		<category><![CDATA[nhibernate]]></category>
		<category><![CDATA[search]]></category>

		<guid isPermaLink="false">http://blogs.intesoft.net/post.aspx?id=fcaee060-fe1d-45eb-9867-5a051d29657b</guid>
		<description><![CDATA[In NHibernate.Search using Lucene.NET Full Text Index (Part 1) we looked at setting up the NHibernate.Search extension to add full-text searching of NHibernate-persisted objects. Next, we&#8217;ll look at how we can perform Google-like searches using the Lucene.NET index and some tips on displaying the results including highlighting the search-terms. Our Book class has the Title,


No related posts.]]></description>
			<content:encoded><![CDATA[</p>
<p>In <a href="http://blogs.intesoft.net/post/2008/03/NHibernateSearch-using-Lucene-NET-Full-Text-Index-Part1.aspx">NHibernate.Search using Lucene.NET Full Text Index (Part 1)</a> we looked at setting up the NHibernate.Search extension to add full-text searching of <a title="NHibernate" href="http://www.nhibernate.org/" target="_blank" rel="tag">NHibernate</a>-persisted objects.</p>
<p>Next, we&#8217;ll look at how we can perform Google-like searches using the <a title="Lucene.NET" href="http://incubator.apache.org/lucene.net/" target="_blank" rel="tag">Lucene.NET</a> index and some tips on displaying the results including highlighting the search-terms.</p>
<p>Our Book class has the Title, Summary, Authors and Publisher field indexed so we&#8217;ll allow searching in any of these fields. However, if a search-term exists in the title it is probably more relevant than if it just exists in the summary so we want to give more priority to certain fields than to others. Likewise, we probably want to be able to specify which fields to search on otherwise we would get books that make mention of &quot;Martin Fowler&quot; in the summary whereas we may want to only see books that have &quot;Martin Fowler&quot; as an author for example.</p>
<p>Also worth mentioning is the Summary field. In the Book class there is a SummaryHtml field which (you&#8217;ll never guess) contains the Html summary retrieved from Amazon and also a Summary field which is the one that is actually indexed. In the full app this text field is generated from the Html content using the <a title="HtmlAgility library" href="http://www.codeplex.com/htmlagilitypack" target="_blank" rel="tag">HtmlAgility library</a>. The reason we want a version of the Summary in plain text is to make indexing easier / more accurate (no HTML tags) and also to allow result fragments to be created: imagine if a section of the SummaryHtml was output &#8211; it could potentially split across an Html element or attribute (producing invalid markup) or include the opening tag but not the matching closing one (producing runaway bold-text for instance).</p>
<p>Back to our example though. To be able to show the highlighted search terms in the results I found it easier to create a special BookSearchResult class that I can return from the data provider &#8211; the highlighting is something Lucene.NET can do for us and avoids us having to write our own presentation code to handle it. Here is the class: </p>
<pre class="csharpcode"><span class="rem">/// &lt;summary&gt;</span>
<span class="rem">/// A wrapper for a book object returned from a full text index query/// with additional properties for highlighted segments</span>
<span class="rem">/// &lt;/summary&gt;</span>
<span class="kwrd">public</span> <span class="kwrd">class</span> BookSearchResult : IBookSearchResult
{
    <span class="kwrd">private</span> <span class="kwrd">readonly</span> IBook _book;
    <span class="kwrd">private</span> <span class="kwrd">string</span> _highlightedTitle;
    <span class="kwrd">private</span> <span class="kwrd">string</span> _highlightedSummary;
    <span class="kwrd">private</span> <span class="kwrd">string</span> _highlightedAuthors;
    <span class="kwrd">private</span> <span class="kwrd">string</span> _highlightedPublisher;

    <span class="rem">/// &lt;summary&gt;</span>
    <span class="rem">/// Initializes a new instance of the &lt;see cref=&quot;BookSearchResult&quot;/&gt; class.</span>
    <span class="rem">/// &lt;/summary&gt;</span>
    <span class="rem">/// &lt;param name=&quot;book&quot;&gt;The book.&lt;/param&gt;</span>
    <span class="kwrd">public</span> BookSearchResult(IBook book)
    {
        _book = book;
    }

    <span class="rem">/// &lt;summary&gt;</span>
    <span class="rem">/// Gets the book.</span>
    <span class="rem">/// &lt;/summary&gt;</span>
    <span class="rem">/// &lt;value&gt;The book.&lt;/value&gt;</span>
    <span class="kwrd">public</span> IBook Book
    {
        get { <span class="kwrd">return</span> _book; }
    }

    <span class="rem">/// &lt;summary&gt;</span>
    <span class="rem">/// Gets or sets the highlighted title.</span>
    <span class="rem">/// &lt;/summary&gt;</span>
    <span class="rem">/// &lt;value&gt;The highlighted title.&lt;/value&gt;</span>
    <span class="kwrd">public</span> <span class="kwrd">string</span> HighlightedTitle
    {
        get
        {
            <span class="kwrd">if</span> (_highlightedTitle == <span class="kwrd">null</span> || _highlightedTitle.Length == 0)
            {
                <span class="kwrd">return</span> _book.Title;
            }
            <span class="kwrd">return</span> _highlightedTitle;
        }
        set { _highlightedTitle = <span class="kwrd">value</span>; }
    }

    <span class="rem">/// &lt;summary&gt;</span>
    <span class="rem">/// Gets or sets the highlighted summary.</span>
    <span class="rem">/// &lt;/summary&gt;</span>
    <span class="rem">/// &lt;value&gt;The highlighted summary.&lt;/value&gt;</span>
    <span class="kwrd">public</span> <span class="kwrd">string</span> HighlightedSummary
    {
        get
        {
            <span class="kwrd">if</span> (_highlightedSummary == <span class="kwrd">null</span> || _highlightedSummary.Length == 0)
            {
                <span class="kwrd">if</span> (_book.Summary == <span class="kwrd">null</span> || _book.Summary.Length &lt; 300)
                {
                    <span class="kwrd">return</span> _book.Summary;
                }
                <span class="kwrd">else</span>
                {
                    <span class="kwrd">return</span> _book.Summary.Substring(0,300) + <span class="str">&quot; ...&quot;</span>;
                }
            }
            <span class="kwrd">return</span> _highlightedSummary;
        }
        set { _highlightedSummary = <span class="kwrd">value</span>; }
    }

    <span class="rem">/// &lt;summary&gt;</span>
    <span class="rem">/// Gets or sets the highlighted authors.</span>
    <span class="rem">/// &lt;/summary&gt;</span>
    <span class="rem">/// &lt;value&gt;The highlighted authors.&lt;/value&gt;</span>
    <span class="kwrd">public</span> <span class="kwrd">string</span> HighlightedAuthors
    {
        get
        {
            <span class="kwrd">if</span> (_highlightedAuthors == <span class="kwrd">null</span> || _highlightedAuthors.Length == 0)
            {
                <span class="kwrd">return</span> _book.Authors;
            }
            <span class="kwrd">return</span> _highlightedAuthors;
        }
        set { _highlightedAuthors = <span class="kwrd">value</span>; }
    }

    <span class="rem">/// &lt;summary&gt;</span>
    <span class="rem">/// Gets or sets the highlighted publisher.</span>
    <span class="rem">/// &lt;/summary&gt;</span>
    <span class="rem">/// &lt;value&gt;The highlighted publisher.&lt;/value&gt;</span>
    <span class="kwrd">public</span> <span class="kwrd">string</span> HighlightedPublisher
    {
        get
        {
            <span class="kwrd">if</span> (_highlightedPublisher == <span class="kwrd">null</span> || _highlightedPublisher.Length == 0)
            {
                <span class="kwrd">return</span> _book.Publisher;
            }
            <span class="kwrd">return</span> _highlightedPublisher;
        }
        set { _highlightedPublisher = <span class="kwrd">value</span>; }
    }
}</pre>
<style type="text/css">
<p>.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}
.csharpcode .lnum { color: #606060; }</style>
<p>&#160;</p>
<p>You&#8217;ll notice that the Highlighted&#8230; fields return the equivalent book field if the highlighted field does not exist. This just saves us having to check whether there is a highlighted term in each field when we&#8217;re building the search result list.</p>
<p>Our data provider will accept a single string consisting of the entered search-terms and return a list of BookSearchResult objects that match. Here is the code and I&#8217;ll then try and explain what it&#8217;s doing:</p>
<pre class="csharpcode"><span class="rem">/// &lt;summary&gt;</span>
<span class="rem">/// Finds the books.</span>
<span class="rem">/// &lt;/summary&gt;</span>
<span class="rem">/// &lt;param name=&quot;query&quot;&gt;The query.&lt;/param&gt;</span>
<span class="rem">/// &lt;returns&gt;&lt;/returns&gt;</span>
<span class="kwrd">public</span> <span class="kwrd">override</span> IList&lt;IBookSearchResult&gt; FindBooks(<span class="kwrd">string</span> query)
{
    IList&lt;IBookSearchResult&gt; results = <span class="kwrd">new</span> List&lt;IBookSearchResult&gt;();

    Analyzer analyzer = <span class="kwrd">new</span> SimpleAnalyzer();
    MultiFieldQueryParser parser = <span class="kwrd">new</span> MultiFieldQueryParser(                                   <span class="kwrd">new</span> <span class="kwrd">string</span>[] { <span class="str">&quot;Title&quot;</span>, <span class="str">&quot;Summary&quot;</span>, <span class="str">&quot;Authors&quot;</span>, <span class="str">&quot;Publisher&quot;</span>},                                    analyzer);
    Query queryObj;

    <span class="kwrd">try</span>
    {
        queryObj = parser.Parse(query);
    }
    <span class="kwrd">catch</span> (ParseException)
    {
        <span class="rem">// TODO: provide feedback to user on failed search expressions</span>
        <span class="kwrd">return</span> results;
    }

    IFullTextSession session = (IFullTextSession) NHibernateHelper.GetCurrentSession();
    IQuery nhQuery = session.CreateFullTextQuery(queryObj, <span class="kwrd">new</span> Type[] {<span class="kwrd">typeof</span> (Book) } );

    IList&lt;IBook&gt; books = nhQuery.List&lt;IBook&gt;();

    IndexReader indexReader = IndexReader.Open(SearchFactory.GetSearchFactory(session)                                         .GetDirectoryProvider(<span class="kwrd">typeof</span> (Book)).Directory);
    Query simplifiedQuery = queryObj.Rewrite(indexReader);

    SimpleHTMLFormatter formatter = <span class="kwrd">new</span> SimpleHTMLFormatter(<span class="str">&quot;&lt;b class='term'&gt;&quot;</span>, <span class="str">&quot;&lt;/b&gt;&quot;</span>);

    Highlighter hTitle = GetHighlighter(simplifiedQuery, formatter, <span class="str">&quot;Title&quot;</span>, 100);
    Highlighter hSummary = GetHighlighter(simplifiedQuery, formatter, <span class="str">&quot;Summary&quot;</span>, 200);
    Highlighter hAuthors = GetHighlighter(simplifiedQuery, formatter, <span class="str">&quot;Authors&quot;</span>, 100);
    Highlighter hPublisher = GetHighlighter(simplifiedQuery, formatter, <span class="str">&quot;Publisher&quot;</span>, 100);

    <span class="kwrd">foreach</span>(IBook book <span class="kwrd">in</span> books)
    {
        IBookSearchResult result = <span class="kwrd">new</span> BookSearchResult(book);

        TokenStream tsTitle = analyzer.TokenStream(<span class="str">&quot;Title&quot;</span>,                               <span class="kwrd">new</span> System.IO.StringReader(book.Title ?? <span class="kwrd">string</span>.Empty));
        result.HighlightedTitle = hTitle.GetBestFragment(tsTitle, book.Title);

        TokenStream tsAuthors = analyzer.TokenStream(<span class="str">&quot;Authors&quot;</span>,                              <span class="kwrd">new</span> System.IO.StringReader(book.Authors ?? <span class="kwrd">string</span>.Empty));
        result.HighlightedAuthors = hAuthors.GetBestFragment(tsAuthors, book.Authors);

        TokenStream tsPublisher = analyzer.TokenStream(<span class="str">&quot;Publisher&quot;</span>,                               <span class="kwrd">new</span> System.IO.StringReader(book.Publisher ?? <span class="kwrd">string</span>.Empty));
        result.HighlightedPublisher = hPublisher.GetBestFragment(tsPublisher, book.Publisher);

        TokenStream tsSummary = analyzer.TokenStream(<span class="str">&quot;Summary&quot;</span>,                               <span class="kwrd">new</span> System.IO.StringReader(book.Summary ?? <span class="kwrd">string</span>.Empty));
        result.HighlightedSummary = hSummary.GetBestFragments(tsSummary,                                     book.Summary, 3, <span class="str">&quot; ... &lt;br /&gt;&lt;br /&gt; ... &quot;</span>);

        results.Add(result);
    }

    <span class="kwrd">return</span> results;
}

<span class="rem">/// &lt;summary&gt;</span>
<span class="rem">/// Gets the highlighter for the given field.</span>
<span class="rem">/// &lt;/summary&gt;</span>
<span class="rem">/// &lt;param name=&quot;query&quot;&gt;The query.&lt;/param&gt;</span>
<span class="rem">/// &lt;param name=&quot;formatter&quot;&gt;The formatter.&lt;/param&gt;</span>
<span class="rem">/// &lt;param name=&quot;field&quot;&gt;The field.&lt;/param&gt;</span>
<span class="rem">/// &lt;param name=&quot;fragmentSize&quot;&gt;Size of the fragment.&lt;/param&gt;</span>
<span class="rem">/// &lt;returns&gt;&lt;/returns&gt;</span>
<span class="kwrd">private</span> <span class="kwrd">static</span> Highlighter GetHighlighter(Query query, Formatter formatter,                                          <span class="kwrd">string</span> field, <span class="kwrd">int</span> fragmentSize)
{
    <span class="rem">// create a new query to contain the terms</span>
    BooleanQuery termsQuery = <span class="kwrd">new</span> BooleanQuery();

    <span class="rem">// extract terms for this field only</span>
    WeightedTerm[] terms = QueryTermExtractor.GetTerms(query, <span class="kwrd">true</span>, field);
    <span class="kwrd">foreach</span> (WeightedTerm term <span class="kwrd">in</span> terms)
    {
        <span class="rem">// create new term query and add to list</span>
        TermQuery termQuery = <span class="kwrd">new</span> TermQuery(<span class="kwrd">new</span> Term(field, term.GetTerm()));
        termsQuery.Add(termQuery, BooleanClause.Occur.SHOULD);
    }

    <span class="rem">// create query scorer based on term queries (field specific)</span>
    QueryScorer scorer = <span class="kwrd">new</span> QueryScorer(termsQuery);

    Highlighter highlighter = <span class="kwrd">new</span> Highlighter(formatter, scorer);
    highlighter.SetTextFragmenter(<span class="kwrd">new</span> SimpleFragmenter(fragmentSize));

    <span class="kwrd">return</span> highlighter;
}</pre>
<pre class="csharpcode">&#160;</pre>
<style type="text/css">
<p>.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}
.csharpcode .lnum { color: #606060; }</style>
<p>First, we parse the user-entered query string indicating that we want to match on the fields Title, Summary, Authors and Publisher using the MultiFieldQueryParser. This turns the user entered search expression into Lucene specific instructions. Most users when searching will enter a simple expression containing the words or phrase that they want to find. If the search term &quot;XML&#8217; is entered for example Lucene will convert this into the expression &quot;Title:XML Summary:XML Authors:XML Publisher:XML&quot; which effectively means &quot;find any record where &#8216;XML&#8217; exists in any of the fields&quot;.</p>
<p>The user can enter specific instructions directly such as &quot;Title:Architecture Authors:Fowler&quot; which means &quot;Find any books that have &#8216;Architecture&#8217; in the Title field or &#8216;Fowler&#8217; in the Authors field&quot;. Boolean expressions can be used to control this further allowing &quot;(Title:Architecture) AND (Authors:Fowler)&quot; to find any books titled &#8216;Architecture&#8217; authored by &#8216;Fowler&#8217;. When specific searches like this have been entered then the MultiFieldQueryParser doesn&#8217;t expand the search to include all fields (except for un-field-prefixed words and phrases).</p>
<p>Incidentally, in the original Book class we included attributes to control the indexing such as [Boost(10)] for the Title. This boosts the relevance of searches on certain fields so a search for &#8216;XML&#8217; in the Title <em><strong>and</strong></em> Summary of a document will rank books with &#8216;XML&#8217; in the Title higher than books that have &#8216;XML&#8217; in the summary &#8211; they are more likely to be what the user is searching for in this case.</p>
<p>Lucene does provide many other ways to define a query but this is simple and easy for this example.</p>
<p>Once we have our Lucene query object we use this to create an NHibernate.Search full-text query to return Book objects. This is where NHibernate and Lucene meet (from a querying point of view). It is possible to combine full-text-queries of Lucene with NHibernate queries of the database &#8211; NHibernate.Search handles the searching and returns the relevant objects.</p>
<p>So, we now have a list of Book objects just the same as if it had come directly from NHibernate except that the results are in order based on the rank provided by the Lucene search.</p>
<p>Now, we&#8217;ll use another part of Lucene to highlight the matches. This is done using the SimpleHTMLFormatter, QueryScorer and Highlighter objects which combined allow us to get a fragment for each field with the search terms highlighted.</p>
<p>Note that the SimpleHtmlFormatter class is <em><strong>not</strong></em> in the main Lucene.Net.dll assembly but instead in a separate contrib assembly called Highlighter.Net.dll &#8211; there are also some other interesting utilities worth exploring in the contrib folder of the Lucene.NET distribution. Remember in <a href="http://blogs.intesoft.net/post/2008/03/NHibernateSearch-using-Lucene-NET-Full-Text-Index-Part1.aspx">Part 1</a> I mentioned that I had problems with assembly references and different versions of Lucene.Net.dll being used by NHibernate.Search so if you have problems building the solution after adding references to these contrib assemblies, consider building NHibernate.Search making sure that it references the same Lucene.Net.dll as the Lucene contrib assemblies were built against.</p>
<p>The Highlighter object for each field has to be based on the query terms for that field only so the original query is re-written and split up so that only the terms searched for that field are used. This isn&#8217;t strictly necessary but I think it makes more sense if when you search for &#8216;Microsoft&#8217; in the Title of a book <em><strong>only</strong></em> that occurrences of &#8216;Microsoft&#8217; in the Summary or Publisher fields are <em><strong>not</strong></em> highlighted: the highlighted results then show clearly which found terms influenced the results. I have split this functionality into a separate GetHighlighter() method.</p>
<p>For example, without doing this a search for &#8216;Title:Microsoft&#8217; incorrectly highlights the occurrences of &#8216;Microsoft&#8217; found within the Author, Publisher and Summary fields even though they did not really contribute to the Book being included in the results or it&#8217;s rank within them:</p>
<p><a href="http://blogs.intesoft.net/image.axd?picture=WindowsLiveWriter/NHibernate.Searchu.NETFullTextIndexPart2_9721/highlight_wrong_2.png"><img style="border-top-width: 0px; border-left-width: 0px; border-bottom-width: 0px; border-right-width: 0px" height="245" alt="highlight_wrong" src="http://blogs.intesoft.net/image.axd?picture=WindowsLiveWriter/NHibernate.Searchu.NETFullTextIndexPart2_9721/highlight_wrong_thumb.png" width="695" border="0" /></a> </p>
<p>By creating the proper Highlighter for each field based on the terms used to search it the search results can be shown correctly without highlighting the un-searched fields / terms:</p>
<p><a href="http://blogs.intesoft.net/image.axd?picture=WindowsLiveWriter/NHibernate.Searchu.NETFullTextIndexPart2_9721/highlight_correct_2.png"><img style="border-top-width: 0px; border-left-width: 0px; border-bottom-width: 0px; border-right-width: 0px" height="195" alt="highlight_correct" src="http://blogs.intesoft.net/image.axd?picture=WindowsLiveWriter/NHibernate.Searchu.NETFullTextIndexPart2_9721/highlight_correct_thumb.png" width="695" border="0" /></a> </p>
<p>Also, not that the fragments produced for the Summary are different &#8211; if a separate terms are used for the Title and Summary then having the Title terms highlighted in the Summary would possibly produce incorrect or sub-standard fragments.</p>
<p>&#160;</p>
<p>Having built our Highlighters we can then iterate over the results creating a BookSearchResult to wrap each book in the result set. The same analyzer used in the initial query is then used to get a TokenStream for each field which the Highlighter instance needs to create the highlighted fragment from.</p>
<p>For the Title, Authors and Publisher fields we return a single Fragment which will normally be the field itself with the highlighted search terms wrapped in &lt;b class=&#8217;term&#8217;&gt; &#8230; &lt;/b&gt; Html tags (courtesy of the SimpleHtmlFormatter class). The highlighted Summary is set to the best 3 fragments separated by &#8216;&#8230; &lt;br /&gt;&lt;br /&gt; &#8230; &#8216;. However big the summary is this ensures that the results contain a similar sized chunk of text with the best fragments shown (those containing the most highlighted terms).</p>
<p>Here is an example of the results for &#8216;Title:Software Summary:Requirements Authors:Steve&#8217; after formatting and CSS applied to show the highlighted terms in yellow:</p>
<p><a href="http://blogs.intesoft.net/image.axd?picture=WindowsLiveWriter/NHibernate.Searchu.NETFullTextIndexPart2_9721/search_results_6.png"><img style="border-top-width: 0px; border-left-width: 0px; border-bottom-width: 0px; border-right-width: 0px" height="950" alt="search_results" src="http://blogs.intesoft.net/image.axd?picture=WindowsLiveWriter/NHibernate.Searchu.NETFullTextIndexPart2_9721/search_results_thumb_2.png" width="665" border="0" /></a> </p>
<p>&#160;</p>
<p>Lucene.NET can do a lot more than I&#8217;ve shown here. I found the best resource for learning about how to use it is the &#8216;Lucene in Action&#8217; book:</p>
<table border="0">
<tbody>
<tr>
<td valign="top"><a href="http://www.amazon.com/gp/redirect.html%3FASIN=1932394281%26tag=ws%26lcode=sp1%26cID=2025%26ccmID=165953%26location=/o/ASIN/1932394281%253FSubscriptionId=0525E2PQ81DD7ZTWTK82"><img src="http://ecx.images-amazon.com/images/I/115SA6PS8SL.jpg" border="1" /></a></td>
<td valign="top"><b>Lucene in Action (In Action series)</b></p>
<p>by Otis Gospodnetic, Erik Hatcher</p>
<p><a href="http://www.amazon.com/gp/redirect.html%3FASIN=1932394281%26tag=ws%26lcode=sp1%26cID=2025%26ccmID=165953%26location=/o/ASIN/1932394281%253FSubscriptionId=0525E2PQ81DD7ZTWTK82">Read more about this book&#8230;</a></td>
</tr>
</tbody>
</table>
<p>Note that this covers the Java version but applies equally well to the .NET port which is practically identical.</p>
<p>&#160;</p>
<p>I hope this has been useful. In Part 3 I&#8217;ll try and demonstrate using the Lucene.NET index to find similar items based on the frequency of shared terms. This can be used to provide &#8216;other books you may like&#8217; or &#8216;blog posts like this one&#8217; type functionality.</p>


<p>No related posts.</p>]]></content:encoded>
			<wfw:commentRss>http://www.captaincodeman.com/2008/03/30/nhibernatesearch-using-lucene-net-full-text-index-part2/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>NHibernate.Search using Lucene.NET Full Text Index (1)</title>
		<link>http://www.captaincodeman.com/2008/03/10/nhibernatesearch-using-lucene-net-full-text-index-part1/</link>
		<comments>http://www.captaincodeman.com/2008/03/10/nhibernatesearch-using-lucene-net-full-text-index-part1/#comments</comments>
		<pubDate>Mon, 10 Mar 2008 21:36:00 +0000</pubDate>
		<dc:creator>Captain Codeman</dc:creator>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[full text indexing]]></category>
		<category><![CDATA[index]]></category>
		<category><![CDATA[lucene]]></category>
		<category><![CDATA[MVC]]></category>
		<category><![CDATA[nhibernate]]></category>
		<category><![CDATA[search]]></category>

		<guid isPermaLink="false">http://blogs.intesoft.net/post.aspx?id=1fc95aeb-3e10-44fb-a5eb-8b7b880d2ff6</guid>
		<description><![CDATA[Ayende added the NHibernate.Search last year but I&#39;ve never seen a great deal of documentation or examples around it so hopefully this post will help others to get started with it. Basically, this addition to NHibernate brings two of the best open source libraries together &#8211; NHibernate as the Object Relational Mapper that persists your


No related posts.]]></description>
			<content:encoded><![CDATA[<p>
<a href="http://www.ayende.com/Blog/" target="_blank">Ayende</a> added the <a href="http://www.ayende.com/Blog/archive/2007/04/02/NHibernate-Search.aspx" target="_blank">NHibernate.Search</a> last year but I&#39;ve never seen a great deal of documentation or examples around it so hopefully this post will help others to get started with it.
</p>
<p>
Basically, this addition to NHibernate brings two of the best open source libraries together &#8211; NHibernate as the Object Relational Mapper that persists your objects to a database and Lucene.NET which provides full-text indexing and query support.
</p>
<p>
So how do you use it?
</p>
<p>
The first problem you will run into is actually finding it. Unfortunately the release of NHibernate does not include it in the \bin although it is there in the source. <a href="http://www.nhibernate.org/" target="_blank">Download the latest version of the NHibernate source</a> (1.2.1 GA as of writing) and compile it to produce the NHibernate.Search.dll assembly.
</p>
<p>
Before you do this though, you <em><strong>may</strong></em> want to also <a href="http://incubator.apache.org/lucene.net/download/" target="_blank">download the latest Lucene.NET release</a> (2.0.004) and replace the Lucene.NET.dll assembly in the NHibernate \lib\net\2.0 folder (I&#39;m assuming you are using .NET 2.0). While the Lucene.NET library has the same version number and did work fine, the sizes are different and I ran into some problems when trying to use some of the extra Lucene.NET assemblies for hit-highlighting and similarity matching.
</p>
<p>
The first step is of course to add a reference to NHibernate.Search.dll to your Visual Studio.NET Project.
</p>
<p>
Next, you need to add some additional properties to the session-factory element of the NHibernate configuration section(normally stored in your web.config file):
</p>
<pre class="csharpcode">
<span class="kwrd">&lt;</span><span class="html">property</span> <span class="attr">name</span><span class="kwrd">=&quot;hibernate.search.default.directory_provider&quot;</span><span class="kwrd">&gt;</span>NHibernate.Search.Storage.FSDirectoryProvider, NHibernate.Search<span class="kwrd">&lt;/</span><span class="html">property</span><span class="kwrd">&gt;</span><span class="kwrd">&lt;</span><span class="html">property</span> <span class="attr">name</span><span class="kwrd">=&quot;hibernate.search.default.indexBase&quot;</span><span class="kwrd">&gt;</span>~/Index<span class="kwrd">&lt;/</span><span class="html">property</span><span class="kwrd">&gt;</span>
</pre>
<p>
&nbsp;
</p>
<p>
If you&#39;ve used Lucene.NET much you will know that it has the concept of different directory providers for storing the indexed such as RAM or FS (File System). The entries above are used to indicate that we want the Lucene index to be stored on the file system and located in the /Index folder of the website (it could of course be outside the website mapped folder). It&#39;s well worth reading a book such as <a href="http://www.manning.com/hatcher2/" target="_blank">Lucene in Action</a> to get a good idea of how Lucene works and what it can do (it&#39;s for the Java version but is still excellent for learning the .NET implementation).
</p>
<p>
The next step requires that you decorate your C# class with some attributes to control the indexing operation. Personally, I don&#39;t like this as it means I need to start referencing NHibernate and Lucene assemblies from my otherwise nice, clean POCO (Plain Old CLR/C# Classes) project. It would have been much nicer IMO if this information could have been put in the NHibernate .hbm.xml mapping files but it&#39;s a small price to pay and some people already use the attribute approach for NHibernate anyway.
</p>
<p>
Here is an example of a Book class for a library application with the additional attributes:
</p>
<pre class="csharpcode">
[Indexed(Index = <span class="str">&quot;Book&quot;</span>)] <span class="kwrd">public</span> <span class="kwrd">class</span> Book : IBook {     <span class="kwrd">private</span> Guid _id;     <span class="kwrd">private</span> <span class="kwrd">string</span> _title;     <span class="kwrd">private</span> <span class="kwrd">string</span> _summary;     <span class="kwrd">private</span> <span class="kwrd">string</span> _summaryHtml;     <span class="kwrd">private</span> <span class="kwrd">string</span> _authors;     <span class="kwrd">private</span> <span class="kwrd">string</span> _url;     <span class="kwrd">private</span> <span class="kwrd">string</span> _smallImageUrl;     <span class="kwrd">private</span> <span class="kwrd">string</span> _mediumImageUrl;     <span class="kwrd">private</span> <span class="kwrd">string</span> _largeImageUrl;     <span class="kwrd">private</span> <span class="kwrd">string</span> _isbn;     <span class="kwrd">private</span> <span class="kwrd">string</span> _published;     <span class="kwrd">private</span> <span class="kwrd">string</span> _publisher;     <span class="kwrd">private</span> <span class="kwrd">string</span> _binding;     [DocumentId]     [FieldBridge(<span class="kwrd">typeof</span>(GuidBridge))]     <span class="kwrd">public</span> Guid Id     {         get { <span class="kwrd">return</span> _id; }         set { _id = <span class="kwrd">value</span>; }     }     [Field(Index.Tokenized, Store = Store.No)]     [Analyzer(<span class="kwrd">typeof</span>(StandardAnalyzer))]     [Boost(2)]     <span class="kwrd">public</span> <span class="kwrd">string</span> Title     {         get { <span class="kwrd">return</span> _title; }         set { _title = <span class="kwrd">value</span>; }     }     [Field(Index.Tokenized, Store = Store.No)]     [Analyzer(<span class="kwrd">typeof</span>(StandardAnalyzer))]     <span class="kwrd">public</span> <span class="kwrd">string</span> Summary     {         get { <span class="kwrd">return</span> _summary; }         set { _summary = <span class="kwrd">value</span>; }     }     <span class="kwrd">public</span> <span class="kwrd">string</span> SummaryHtml     {         get         {             <span class="kwrd">if</span> (_summaryHtml == <span class="kwrd">null</span> || _summaryHtml.Length == 0)             {                 <span class="kwrd">return</span> _summary;             }             <span class="kwrd">return</span> _summaryHtml;         }         set { _summaryHtml = <span class="kwrd">value</span>; }     }     [Field(Index.Tokenized, Store = Store.No)]     [Analyzer(<span class="kwrd">typeof</span>(StandardAnalyzer))]     <span class="kwrd">public</span> <span class="kwrd">string</span> Authors     {         get { <span class="kwrd">return</span> _authors; }         set { _authors = <span class="kwrd">value</span>; }     }     <span class="kwrd">public</span> <span class="kwrd">string</span> Url     {         get { <span class="kwrd">return</span> _url; }         set { _url = <span class="kwrd">value</span>; }     }     <span class="kwrd">public</span> <span class="kwrd">string</span> SmallImageUrl     {         get { <span class="kwrd">return</span> _smallImageUrl; }         set { _smallImageUrl = <span class="kwrd">value</span>; }     }     <span class="kwrd">public</span> <span class="kwrd">string</span> MediumImageUrl     {         get { <span class="kwrd">return</span> _mediumImageUrl; }         set { _mediumImageUrl = <span class="kwrd">value</span>; }     }     <span class="kwrd">public</span> <span class="kwrd">string</span> LargeImageUrl     {         get { <span class="kwrd">return</span> _largeImageUrl; }         set { _largeImageUrl = <span class="kwrd">value</span>; }     }     [Field(Index.UnTokenized, Store = Store.Yes)]     <span class="kwrd">public</span> <span class="kwrd">string</span> Isbn     {         get { <span class="kwrd">return</span> _isbn; }         set { _isbn = <span class="kwrd">value</span>; }     }     [Field(Index.UnTokenized, Store = Store.No)]     <span class="kwrd">public</span> <span class="kwrd">string</span> Published     {         get { <span class="kwrd">return</span> _published; }         set { _published = <span class="kwrd">value</span>; }     }     [Field(Index.Tokenized, Store = Store.No)]     [Analyzer(<span class="kwrd">typeof</span>(StandardAnalyzer))]     <span class="kwrd">public</span> <span class="kwrd">string</span> Publisher     {         get { <span class="kwrd">return</span> _publisher; }         set { _publisher = <span class="kwrd">value</span>; }     }     <span class="kwrd">public</span> <span class="kwrd">string</span> Binding     {         get { <span class="kwrd">return</span> _binding; }         set { _binding = <span class="kwrd">value</span>; }     } }
</pre>
<p>
Now we&#39;re ready to start using it from NHibernate. To do this we need to create a FullTextSession and use this instead of the regular NHibernate Session (which it wraps / extends):
</p>
<pre class="csharpcode">
ISession session = sessionFactory.OpenSession(<span class="kwrd">new</span> SearchInterceptor());IFullTextSession fullTextSession = Search.CreateFullTextSession(session);
</pre>
<p>
&nbsp;
</p>
<p>
And that&#39;s it. You can use the IFullTextSession in place of the regular ISession (even casting it for places where you are just doing normal NHibernate operations). All the magic happens inside NHibernate.Search &#8211; when you add, update or delete records the &#39;documents&#39; in the Lucene index are automatically updated which provides you with an excellent Full Text index without a Windows Service in sight!
</p>
<p>
You can check that it&#39;s working by looking in the Index folder &#8211; there should be a &#39;Book&#39; folder containing the Lucene index files (with CFS extensions).
</p>
<p>
In the next post I&#39;ll demonstrate using the index to do some queries including hit-highlighting for presenting the results but for now you may want to download and try <a href="http://www.getopt.org/luke/" target="_blank">Luke &#8211; a Java program to browser Lucene index catalogs</a> (the file format is identical between the two implementations).</p>


<p>No related posts.</p>]]></content:encoded>
			<wfw:commentRss>http://www.captaincodeman.com/2008/03/10/nhibernatesearch-using-lucene-net-full-text-index-part1/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>

