Skip to content

Instantly share code, notes, and snippets.

@SpencerLynn
Last active August 29, 2015 14:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save SpencerLynn/a8b52a664e4a4a03a18a to your computer and use it in GitHub Desktop.
Save SpencerLynn/a8b52a664e4a4a03a18a to your computer and use it in GitHub Desktop.
public class Indexer
{
private Dictionary<string, List<string>> terms =
new Dictionary<string, List<string>>(StringComparer.OrdinalIgnoreCase);
private Dictionary<string, List<string>> itemsByTerm =
new Dictionary<string, List<string>>();
public void Index(string docId, string text)
{
// First check to see if we already have anything for this docId
if (itemsByTerm.ContainsKey(docId))
{
RemoveItemsByTerm(docId);
}
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);
}
List<string> docs;
if (itemsByTerm.TryGetValue(docId, out docs) == false)
{
docs = new List<string>();
itemsByTerm[docId] = docs;
}
docs.AddRange(words);
}
public List<string> Query(string term)
{
List<string> val;
terms.TryGetValue(term, out val);
return val ?? new List<string>();
}
public void Delete(string docId)
{
RemoveItemsByTerm(docId);
}
private void RemoveItemsByTerm(string docId)
{
var termsWithItem = itemsByTerm[docId];
foreach (var term in termsWithItem)
{
terms.Remove(term);
}
itemsByTerm.Remove(docId);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment