SearchBox/SearchBox/InvertedIndex.cs

42 lines
1.0 KiB
C#

using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
namespace SearchBox
{
public class InvertedIndex
{
private ConcurrentDictionary<string, ConcurrentDictionary<int, List<int>>> invertedIndex = new ConcurrentDictionary<string, ConcurrentDictionary<int, List<int>>>();
public InvertedIndex()
{
}
public bool AddIndex(int pageId, Index newIndex)
{
foreach (KeyValuePair<string, List<int>> token in newIndex)
{
if (!invertedIndex.ContainsKey(token.Key) &&
!invertedIndex.TryAdd(token.Key, new ConcurrentDictionary<int, List<int>>()))
return false;
if (!invertedIndex[token.Key].TryAdd(pageId, token.Value))
return false;
}
return true;
}
public bool RemoveIndex(int pageId, Index newIndex)
{
foreach (string token in newIndex.Tokens())
{
if (!invertedIndex.ContainsKey(token) || !invertedIndex[token].ContainsKey(pageId)) continue;
if (!invertedIndex[token].TryRemove(pageId, out List<int> noop))
return false;
}
return false;
}
}
}