Click here to Skip to main content
Click here to Skip to main content
Add your own
alternative version

Lucene.Net ultra fast search for MVC or WebForms site => made easy!

, 22 Aug 2013
Step-by-step tutorial for any developer who wishes to get Lucene.Net search working with their web site or app really quickly!
Lucene.Net-search-MVC-sample-site-master-noexe.zip
Lucene.Net-search-MVC-sample-site-master
.gitignore
.nuget
NuGet.targets
LuceneSearch.Data
Model
Properties
Repository
LuceneSearch.Library
Properties
LuceneSearch.Mvc
Archives
ClearLuceneIndex.old
Content
kickstart
fonts
base
icomoon-webfont.eot
icomoon-webfont.svg
icomoon-webfont.ttf
icomoon-webfont.woff
social
icomoonsocial-webfont.eot
icomoonsocial-webfont.svg
icomoonsocial-webfont.ttf
icomoonsocial-webfont.woff
img
breadcrumbs-bg.gif
chosen-sprite.png
fancybox
blank.gif
fancy_close.png
fancy_loading.png
fancy_nav_left.png
fancy_nav_right.png
fancy_shadow_e.png
fancy_shadow_n.png
fancy_shadow_ne.png
fancy_shadow_nw.png
fancy_shadow_s.png
fancy_shadow_se.png
fancy_shadow_sw.png
fancy_shadow_w.png
fancy_title_left.png
fancy_title_main.png
fancy_title_over.png
fancy_title_right.png
fancybox-x.png
fancybox-y.png
fancybox.png
grid.png
icon-arrow-right.png
icon-check.png
rte
link.png
link_break.png
picture_empty.png
text_align_center.png
text_align_left.png
text_align_right.png
text_bold.png
text_italic.png
text_list_bullets.png
text_list_numbers.png
text_strikethrough.png
text_subscript.png
text_superscript.png
Controllers
Global.asax
Properties
Scripts
ViewModels
Views
Home
Shared
LuceneSearch.WebForms
Content
kickstart
fonts
base
icomoon-webfont.eot
icomoon-webfont.svg
icomoon-webfont.ttf
icomoon-webfont.woff
social
icomoonsocial-webfont.eot
icomoonsocial-webfont.svg
icomoonsocial-webfont.ttf
icomoonsocial-webfont.woff
img
breadcrumbs-bg.gif
chosen-sprite.png
fancybox
blank.gif
fancy_close.png
fancy_loading.png
fancy_nav_left.png
fancy_nav_right.png
fancy_shadow_e.png
fancy_shadow_n.png
fancy_shadow_ne.png
fancy_shadow_nw.png
fancy_shadow_s.png
fancy_shadow_se.png
fancy_shadow_sw.png
fancy_shadow_w.png
fancy_title_left.png
fancy_title_main.png
fancy_title_over.png
fancy_title_right.png
fancybox-x.png
fancybox-y.png
fancybox.png
grid.png
icon-arrow-right.png
icon-check.png
rte
link.png
link_break.png
picture_empty.png
text_align_center.png
text_align_left.png
text_align_right.png
text_bold.png
text_italic.png
text_list_bullets.png
text_list_numbers.png
text_strikethrough.png
text_subscript.png
text_superscript.png
Global.asax
Properties
Scripts
ViewModels
README.md
Lucene.Net-search-MVC-sample-site-master.zip
.gitignore
NuGet.exe
NuGet.targets
ClearLuceneIndex.old
icomoon-webfont.eot
icomoon-webfont.svg
icomoon-webfont.ttf
icomoon-webfont.woff
icomoonsocial-webfont.eot
icomoonsocial-webfont.svg
icomoonsocial-webfont.ttf
icomoonsocial-webfont.woff
breadcrumbs-bg.gif
chosen-sprite.png
blank.gif
fancy_close.png
fancy_loading.png
fancy_nav_left.png
fancy_nav_right.png
fancy_shadow_e.png
fancy_shadow_n.png
fancy_shadow_ne.png
fancy_shadow_nw.png
fancy_shadow_s.png
fancy_shadow_se.png
fancy_shadow_sw.png
fancy_shadow_w.png
fancy_title_left.png
fancy_title_main.png
fancy_title_over.png
fancy_title_right.png
fancybox-x.png
fancybox-y.png
fancybox.png
grid.png
icon-arrow-right.png
icon-check.png
link.png
link_break.png
picture_empty.png
text_align_center.png
text_align_left.png
text_align_right.png
text_bold.png
text_italic.png
text_list_bullets.png
text_list_numbers.png
text_strikethrough.png
text_subscript.png
text_superscript.png
Global.asax
icomoon-webfont.eot
icomoon-webfont.svg
icomoon-webfont.ttf
icomoon-webfont.woff
icomoonsocial-webfont.eot
icomoonsocial-webfont.svg
icomoonsocial-webfont.ttf
icomoonsocial-webfont.woff
breadcrumbs-bg.gif
chosen-sprite.png
blank.gif
fancy_close.png
fancy_loading.png
fancy_nav_left.png
fancy_nav_right.png
fancy_shadow_e.png
fancy_shadow_n.png
fancy_shadow_ne.png
fancy_shadow_nw.png
fancy_shadow_s.png
fancy_shadow_se.png
fancy_shadow_sw.png
fancy_shadow_w.png
fancy_title_left.png
fancy_title_main.png
fancy_title_over.png
fancy_title_right.png
fancybox-x.png
fancybox-y.png
fancybox.png
grid.png
icon-arrow-right.png
icon-check.png
link.png
link_break.png
picture_empty.png
text_align_center.png
text_align_left.png
text_align_right.png
text_bold.png
text_italic.png
text_list_bullets.png
text_list_numbers.png
text_strikethrough.png
text_subscript.png
text_superscript.png
Global.asax
README.md
mvclucenesampleapp.zip
MvcLuceneSampleApp
MvcLuceneSampleApp
Archives
ClearLuceneIndex.old
bin
ICSharpCode.SharpZipLib.dll
Lucene.Net.dll
MvcLuceneSampleApp.dll
MvcLuceneSampleApp.pdb
Content
Controllers
Global.asax
Lucene
Model
MvcLuceneSampleApp.csproj.user
Properties
Scripts
ZeroClipboard.swf
ViewModels
Views
Home
Shared
packages
Lucene.Net.2.9.4.1
lib
net40
Lucene.Net.dll
Lucene.Net.2.9.4.1.nupkg
SharpZipLib.0.86.0
lib
11
ICSharpCode.SharpZipLib.dll
20
ICSharpCode.SharpZipLib.dll
SL3
SharpZipLib.Silverlight3.dll
SL4
SharpZipLib.Silverlight4.dll
SharpZipLib.0.86.0.nupkg
README
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web.UI;
using System.Web.UI.WebControls;
using LuceneSearch.Service;
using LuceneSearch.Data;
using LuceneSearch.Model;
using WebFormsLuceneSampleApp.ViewModels;

namespace WebFormsLuceneSampleApp {
  public partial class _DefaultPage : Page {
    protected void Page_Load(object sender, EventArgs e) {
      if (!IsPostBack)
        bindData();
    }

    public DefaultViewModel Model;

    private string getSearchTerm() {
      return Request.QueryString["searchTerm"] ?? "";
    }
    private string getSearchField() {
      return Request.QueryString["searchField"] ?? "";
    }
    private string getSearchType() {
      return Request.QueryString["type"] ?? "";
    }
    private string getLimit() {
      return Request.QueryString["limit"] ?? "";
    }

    private void bindData() {
      Model = getDefaultViewModel(getSearchTerm(), getSearchField(), getSearchType());
      
      var limit = getLimit() == "" ? 3 : Convert.ToInt32(getLimit());
      if (limit > 0) {
        litDatabaseRecordsCount.Text =
          "<div class=\"margin_top10\">And <b>" + (Model.AllSampleData.Count() - limit) + "</b> more records... " +
          "(<a href=\"" + Request.ApplicationPath + "?limit=0\">See All</a>)</div>";
        lvDatabase.DataSource = Model.AllSampleData.Take(limit);
      }
      else
        lvDatabase.DataSource = Model.AllSampleData;
      lvDatabase.DataBind();
      
      var searchIndex = Model.AllSearchIndexData;
      if (getSearchTerm() != string.Empty)
        searchIndex = Model.SampleSearchResults;

      lvSearchIndex.DataSource = searchIndex;
      lvSearchIndex.DataBind();

      ddlSearchFields.DataValueField = "Value";
      ddlSearchFields.DataTextField = "Text";
      ddlSearchFields.DataSource = Model.SearchFieldList;
      ddlSearchFields.DataBind();

      txtSearch.Text = getSearchTerm();
      ddlSearchFields.SelectedValue = getSearchField();
      chkSearchDefault.Checked = getSearchType() == "default";
    }

    private DefaultViewModel getDefaultViewModel(string searchTerm, string searchField, string type = "") {
      // create default Lucene search index directory
      if (!Directory.Exists(GoLucene._luceneDir)) Directory.CreateDirectory(GoLucene._luceneDir);

      // perform Lucene search
      IEnumerable<SampleData> searchResults = new List<SampleData>();
      if (string.IsNullOrEmpty(type))
        searchResults = string.IsNullOrEmpty(searchField)
                           ? GoLucene.Search(searchTerm)
                           : GoLucene.Search(searchTerm, searchField);
      else if (type == "default")
        searchResults = string.IsNullOrEmpty(searchField)
                           ? GoLucene.SearchDefault(searchTerm)
                           : GoLucene.SearchDefault(searchTerm, searchField);

      // setup and return view model
      var search_field_list = new
        List<SelectedList> {
                             new SelectedList {Text = "(All Fields)", Value = ""},
                             new SelectedList {Text = "Id", Value = "Id"},
                             new SelectedList {Text = "Name", Value = "Name"},
                             new SelectedList {Text = "Description", Value = "Description"}
                           };
      return new DefaultViewModel {
                                  AllSampleData = SampleDataRepository.GetAll(),
                                  AllSearchIndexData = GoLucene.GetAllIndexRecords(),
                                  SampleData = new SampleData {Id = 9, Name = "El-Paso", Description = "City in Texas"},
                                  SampleSearchResults = searchResults,
                                  SearchFieldList = search_field_list,
                                };
    }

    private void createIndex() {
      GoLucene.AddUpdateLuceneIndex(SampleDataRepository.GetAll());
      litResult.Text = "Search index was created successfully!";
      bindData();
    }

    private void addToIndex(SampleData sampleData) {
      GoLucene.AddUpdateLuceneIndex(sampleData);
      litResult.Text = "Record was added to search index successfully!";
      bindData();
    }

    private void clearIndex() {
      if (GoLucene.ClearLuceneIndex())
        litResult.Text = "Search index was cleared successfully!";
      else
        litResult.Text = "Index is locked and cannot be cleared, try again later or clear manually!";
      bindData();
    }

    private void clearIndexRecord(int id) {
			GoLucene.ClearLuceneIndexRecord(id);
      litResult.Text = "Search index record was deleted successfully!";
      bindData();
		}

    private void optimizeIndex() {
			GoLucene.Optimize();
      litResult.Text = "Search index was optimized successfully!";
      bindData();
		}
    
    // List views
    protected void lvSearchIndex_OnItemDeleting(object sender, ListViewDeleteEventArgs e) {
      var recordId = (int) lvSearchIndex.DataKeys[e.ItemIndex].Value;
      clearIndexRecord(recordId);
    }
    
    // Form events
    protected void CreateIndex_Click(object sender, EventArgs e) {
      createIndex();
    }
    protected void lnkOptimizeIndex_Click(object sender, EventArgs e) {
      optimizeIndex();
    }
    protected void lnkClearIndex_Click(object sender, EventArgs e) {
      clearIndex();
    }
    protected void btnAddUpdate_Click(object sender, EventArgs e) {
      int id;
      if (!int.TryParse(txtId.Text, out id)) {
        litResultFail.Text = "'Id' must be a number!";
        return;
      }
      addToIndex
        (new SampleData {
                          Id = id,
                          Name = txtName.Text,
                          Description = txtDescription.Text
                        });
    }
    protected void btnSearch_Click(object sender, EventArgs e) {
      Response.Redirect(Request.ApplicationPath +
                        "?searchTerm=" + txtSearch.Text +
                        "&searchField=" + ddlSearchFields.SelectedValue +
                        "&type=" + (chkSearchDefault.Checked ? "default" : "")
        );
    }

  }
}

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

Mikhail-T
Web Developer
United States United States
MVC, .NET, AngularJS, JQuery, and POST/GET - all are my good friends!

| Advertise | Privacy | Mobile
Web04 | 2.8.140821.2 | Last Updated 22 Aug 2013
Article Copyright 2012 by Mikhail-T
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid