Skip to content

Instantly share code, notes, and snippets.

@popcatalin81
Last active August 29, 2015 14:18
Show Gist options
  • Save popcatalin81/95fadb2db3b41d47504e to your computer and use it in GitHub Desktop.
Save popcatalin81/95fadb2db3b41d47504e to your computer and use it in GitHub Desktop.
public class Indexer
{
private Dictionary<string, HashSet<string>> terms = new Dictionary<string, HashSet<string>>(StringComparer.OrdinalIgnoreCase);
private Dictionary<string, HashSet<string>> docTerms = new Dictionary<string, HashSet<string>>(StringComparer.OrdinalIgnoreCase);
public void Index(string docId, string text)
{
var words = new HashSet<string>(text.Split(), StringComparer.OrdinalIgnoreCase);
HashSet<string> toRemove;
if (docTerms.TryGetValue(docId, out toRemove))
{
toRemove.ExceptWith(words);
}
docTerms[docId] = words;
foreach (var term in words)
{
HashSet<string> val;
if (terms.TryGetValue(term, out val) == false)
{
val = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
terms[term] = val;
}
val.Add(docId);
}
if (toRemove != null)
{
foreach (var term in toRemove)
{
RemoveTerm(term, docId);
}
}
}
public List<string> Query(string term)
{
HashSet<string> val;
terms.TryGetValue(term, out val);
return new List<string>(val ?? Enumerable.Empty<string>());
}
public void Delete(string docId)
{
HashSet<string> toRemove;
if (docTerms.TryGetValue(docId, out toRemove))
{
foreach (var term in toRemove)
{
RemoveTerm(term, docId);
}
docTerms.Remove(docId);
}
}
private void RemoveTerm(string term, string docId)
{
HashSet<string> val;
if (terms.TryGetValue(term, out val))
{
val.Remove(docId);
if (val.Count == 0)
{
terms.Remove(term);
}
}
}
}
public class IndexTests
{
[Fact]
public void CanIndexAndQuery()
{
var index = new Indexer();
index.Index("users/1", "Oren Eini");
index.Index("users/2", "Hibernating Rhinos");
Assert.Contains("users/1", index.Query("eini"));
Assert.Contains("users/2", index.Query("rhinos"));
}
[Fact]
public void CanUpdate()
{
var index = new Indexer();
index.Index("users/1", "Oren Eini");
//updating
index.Index("users/1", "Ayende Rahien");
Assert.Contains("users/1", index.Query("Rahien"));
Assert.Empty(index.Query("eini"));
}
[Fact]
public void CanDelete()
{
var index = new Indexer();
index.Index("users/1", "Oren Eini");
index.Index("users/2", "Hibernating Rhinos");
index.Index("users/3", "Ayende Rahien Hibernating Rhinos");
//updating
index.Delete("users/3");
Assert.Contains("users/1", index.Query("Oren"));
Assert.Contains("users/2", index.Query("rhinos"));
Assert.Empty(index.Query("ayende"));
}
}
@clupasq
Copy link

clupasq commented Mar 30, 2015

If you rename the file to have the .cs extension, the code will be shown with syntax highlighting. This helps readability IMHO.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment