4

我正在学习如何使用 LiteDB。这是我用来将 .Net 对象插入数据库的一些 C# 代码:

     // Create new YacksProjectInfo object and insert it into the database
     YacksProjectInfo projectInfo = new YacksProjectInfo(AssemblyName, moduleNumber);
     yacksProjects.Insert(projectInfo);  // Id field generated automatically
     yacksProjects.EnsureIndex((YacksProjectInfo x) => x.ProjectName);
     yacksProjects.EnsureIndex((YacksProjectInfo x) => x.ModuleNumber);

换句话说,每次向数据库添加新对象时,我都会使用 EnsureIndex() 方法。但我猜这不是必需的,您只需要在插入第一个对象后执行一次。

有人可以确认是否每次都需要完成 EnsureIndex(),或者一次是否足够?

4

1 回答 1

6

我在这里找到了答案(在找到另外两个提出相同问题的人之后,我对提出一个具有相当明显答案的问题并不感到尴尬):https ://github.com/mbdavid/LiteDB/issues /789

去引用:

“我需要在每次写操作时调用它 EnsureIndex 吗?”

“我也在想同样的事情。你到底什么时候调用 EnsureIndex?你是第一次向数据库添加新集合来设置索引时使用它,还是每次调用 GetCollection 后都需要使用它例如?文档对此不是很清楚。

由创建 LiteDB 的@mbdavid 回答:

“如果需要,您需要在对数据库创建索引运行查询之前调用 EnsureIndex。如果已创建索引(使用相同的 EnsureIndex),EnsureIndex 将什么也不做。因此,为了实用,创建所有索引的最佳位置是在数据库初始化中”

顺便说一句,我在使用 EnsureIndex() 时还学到了一些东西——它有第二个参数“唯一”,一个布尔值。所以我猜想将这个设置为 true(当相关时)会提高效率,并且还可以防止插入具有非唯一索引的新文档。

所以现在我创建的 LiteDB 数据库集合如下所示:

        // Get the collection (or create, if doesn't exist)
        LiteCollection<YacksProjectInfo> yacksProjects = 
                                  liteDatabase.GetCollection<YacksProjectInfo>("YacksProjects");

        // Index current and future documents using ProjectName and ModuleNumber properties
        yacksProjects.EnsureIndex((YacksProjectInfo x) => x.ProjectName, true);
        yacksProjects.EnsureIndex((YacksProjectInfo x) => x.ModuleNumber, true);
于 2018-03-11T04:35:00.060 回答