This tutorial is intended to be a quick introduction to SphinxConnector.NET's fluent API. It assumes that you have a basic understanding of how Sphinx works, if you are new to Sphinx, you can find an introduction here. We'll cover the initial setup and executing full-text queries. We will also demonstrate saving and deleting documents from real-time indexes.

You should have a working local installation of Sphinx that is configured to listen on 127.0.0.1 and port 9306 using the MySQL protocol. You also need to disable the legacy SphinxQL quirks compatiblity mode by setting compat_sphinxql_magics = 0 in your sphinx.conf file (if you haven't already done so). Alternatively, you can also download a fully working version of this guide.

Installing SphinxConnector.NET

The recommended way of installing SphinxConnector.NET is via NuGet. This way, all necessary files will be added to your project. If you downloaded the ZIP package, please add references to the files contained in the folder named Required DLLs to your project.

Creating a Document Model

Suppose that you have the following index definition for a catalog of books:

index books
{
  type              = rt
  path              = books
  
  rt_field          = title
  rt_attr_string    = title
  rt_field          = author
  rt_attr_string    = author
  rt_attr_float     = price
  rt_attr_timestamp = releasedate
  rt_attr_uint      = ebookavailable
  rt_attr_multi     = categories
  
  charset_table     = 0..9, A..Z->a..z, a..z
  charset_type      = utf-8
}

We will now create a model class representing a document from this index. The minimum requirement for a document class is that is has a property representing the document id. With the default conventions, SphinxConnector.NET will be looking for a property (or a field) named Id. The name of the class should be the index name without the 's' at the end.

public class Book
{
    public int Id { get; set; }
}

Next, we'll add properties for the different attributes to our document class:

public class Book
{
   public Book()
   {
       Title = String.Empty;
       Author = String.Empty;
   }

   public int Id { get; set; }
   public string Title { get; set; }
   public string Author { get; set; }
   public decimal Price { get; set; }
   public bool EbookAvailable { get; set; }
   public DateTime ReleaseDate { get; set; }

   public IList<long> Categories { get;set; }
   
   public int Weight { get; set; }
}

Note that we are initializing Title and Author with String.Empty as the default value. As Sphinx does not know how to handle NULL values, SphinxConnector.NET would throw an exception if one of these properties were NULL.

Also notice that we've added a property named Weight, which allows us to use the weight that a document gets assigned by Sphinx in a query. This is optional, so we could have omitted this, if we didn't want to use the weight in our queries.

Initial Setup

Before we can use the fluent API for our queries, we need to create and initialize an instance of the FulltextStore class. Make sure to include the following using statement:

using SphinxConnector.FluentApi;

This class exposes properties to configure conventions, connection strings, etc. and also serves as a factory for instances of IFulltextSession. You'll only need to create this class once per application, usually in your IoC-Container or the entry method of your application.

IFulltextStore fulltextStore = new FulltextStore().Initialize();

As we are using the default conventions, we don't have to configure anything. SphinxConnector.NET will map the Book class to the index 'books' and treat the property names converted to lower case, as names for the attributes.

To locate the connection string, SphinxConnector.NET will look at the app.config file for a connection string named 'sphinx' and use that if present. If it doesn't find one, it'll check if another connection string has been configured via IFulltextStore.ConnectionString. Otherwise the default connection string of 'datasource=localhost;port=9306' will be used.

Executing a Full-Text Query

Queries are executed via the Query method of the IFulltextSession interface. To start a session you call the StartSession method provided by IFulltextStore. A separate session should be created for each incoming (web-)request.

using (IFulltextSession session = fulltextStore.StartSession())
{
    var results = session.Query<Book>().
                          Match("@author Martin @* A Song of Ice and Fire").
                          Where(x => x.EbookAvailable).
                          OrderBy(x => x.Price).                                      
                          Select(x => new { x.Title, x.Price }).
                          ToList();                
}

Saving and Deleting Documents

To save a document in a real-time index, the IFulltextSession interface provides the method Save. Save takes either a single document or an enumerable of documents as an argument.

using (IFulltextSession session = fulltextStore.StartSession())
{
    session.Save(new Book
    {
        Id = 1,
        Author = "George R.R. Martin",
        Title = "A Game of Thrones: A Song of Ice and Fire: Book One",
        EbookAvailable = true,
        Categories = new long[] { 1, 2 },
        Price = 5.60m,
        ReleaseDate = new DateTime(1997, 8, 4)
     });
     
     session.FlushChanges();
}

Notice the call to FlushChanges at the end of the using statement. All changes that you make within a session are only persisted the moment you call FlushChanges. All statements that are executed then, are made in a single transaction (one per index).

Deleting documents from a real-time index is done via the Delete method of the IFulltextSession interface. You can either provide the id(s) of the document(s) to delete or an instance of a document that should be deleted:

using (IFulltextSession session = fulltextStore.StartSession())
{
    session.Delete<Book>(1, 2, 3);
    
    session.FlushChanges();
}

Want some extra help?

No problem, we offer consulting and custom development for Sphinx and .NET! Interested?
To get in touch drop us a line!

 Download this Example