以下是一个简单的倒排索引的 Java 实现:
import java.util.*;
public class InvertedIndex {
private Map<String, List<Integer>> index; // 倒排索引,词项到文档 ID 的映射
public InvertedIndex() {
this.index = new HashMap<>();
}
// 添加文档到倒排索引
public void addDocument(int docId, String[] terms) {
for (String term : terms) {
if (!index.containsKey(term)) {
index.put(term, new ArrayList<>());
}
index.get(term).add(docId);
}
}
// 根据词项查询倒排列表
public List<Integer> search(String term) {
return index.getOrDefault(term, Collections.emptyList());
}
public static void main(String[] args) {
InvertedIndex invertedIndex = new InvertedIndex();
invertedIndex.addDocument(1, new String[]{"Elasticsearch", "搜索"});
invertedIndex.addDocument(2, new String[]{"Elasticsearch", "分布式"});
invertedIndex.addDocument(3, new String[]{"搜索", "技术"});
System.out.println("倒排列表 \"Elasticsearch\": " + invertedIndex.search("Elasticsearch"));
System.out.println("倒排列表 \"搜索\": " + invertedIndex.search("搜索"));
System.out.println("倒排列表 \"分布式\": " + invertedIndex.search("分布式"));
System.out.println("倒排列表 \"技术\": " + invertedIndex.search("技术"));
}
}
这个实现创建了一个简单的倒排索引数据结构 InvertedIndex,其中使用 Map<String, List<Integer>> 存储了词项到文档 ID 的映射关系。addDocument 方法用于添加文档到倒排索引,search 方法用于根据词项查询倒排列表。在 main 方法中,我们添加了一些文档并进行了一些查询操作来测试倒排索引的功能。