Skip to content

Instantly share code, notes, and snippets.

@dlidstrom
Created March 30, 2015 10:44
Show Gist options
  • Save dlidstrom/f26ffdc5174bc1464359 to your computer and use it in GitHub Desktop.
Save dlidstrom/f26ffdc5174bc1464359 to your computer and use it in GitHub Desktop.
Indexer with tests
public class Indexer
{
private readonly Dictionary<string, List<string>> terms =
new Dictionary<string, List<string>>(StringComparer.OrdinalIgnoreCase);
private readonly Dictionary<string, List<string>> docsTerms =
new Dictionary<string, List<string>>(StringComparer.OrdinalIgnoreCase);
public void Index(string docId, string text)
{
List<string> docTerms;
if (docsTerms.TryGetValue(docId, out docTerms) == false)
{
docTerms = new List<string>();
docsTerms[docId] = docTerms;
}
foreach (var docTerm in docTerms)
{
terms.Remove(docTerm);
}
var words = text.Split();
foreach (var term in words)
{
List<string> val;
if (terms.TryGetValue(term, out val) == false)
{
val = new List<string>();
terms[term] = val;
}
val.Add(docId);
docTerms.Add(term);
}
}
public List<string> Query(string term)
{
List<string> val;
terms.TryGetValue(term, out val);
return val ?? new List<string>();
}
public void Delete(string docId)
{
var docTerms = docsTerms[docId];
foreach (var term in docTerms)
{
terms.Remove(term);
}
}
}
[TestFixture]
public class IndexTests
{
[Test]
public void CanIndexAndQuery()
{
var index = new Indexer();
index.Index("users/1", "Daniel Lidstrom");
index.Index("users/2", "index tests");
Assert.Contains("users/1", index.Query("lidstrom"));
Assert.Contains("users/2", index.Query("tests"));
}
[Test]
public void CanUpdate()
{
var index = new Indexer();
index.Index("users/1", "Daniel Lidstrom");
// updating
index.Index("users/1", "Lars Nilsson");
Assert.Contains("users/1", index.Query("nilsson"));
Assert.That(index.Query("lidstrom"), Is.Empty);
}
[Test]
public void CanDelete()
{
var index = new Indexer();
index.Index("users/1", "Daniel Lidstrom");
// deleting
index.Delete("users/1");
Assert.That(index.Query("lidstrom"), Is.Empty);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment