【问题标题】:Room database: What is Index specific columns (indices and @Index) and how to use it?房间数据库:什么是索引特定列(索引和@Index)以及如何使用它?
【发布时间】:2019-07-20 00:58:03
【问题描述】:

我指的是房间数据库的索引特定列。

下面是一些示例代码写在这里https://developer.android.com/training/data-storage/room/defining-data#column-indexing

示例代码 1:

    @Entity(indices = {@Index("name"),
        @Index(value = {"last_name", "address"})})
public class User {
    @PrimaryKey
    public int id;

    public String firstName;
    public String address;

    @ColumnInfo(name = "last_name")
    public String lastName;

    @Ignore
    Bitmap picture;
}

示例代码 2:

@Entity(indices = {@Index(value = {"first_name", "last_name"},
        unique = true)})
public class User {
    @PrimaryKey
    public int id;

    @ColumnInfo(name = "first_name")
    public String firstName;

    @ColumnInfo(name = "last_name")
    public String lastName;

    @Ignore
    Bitmap picture;
}

这在 android 的房间文档中有所描述, 我已经使用索引来表示列的唯一性,但是上面的代码意味着什么,谁能解释一下?

Q1:索引和@Index有什么用?
Q2:@Index("name")@Index(value = {"last_name", "address"})有什么区别?

【问题讨论】:

  • 索引不是为了唯一性。这是为了在给定的列上更快地搜索。如何生成唯一值可以在这里找到:stackoverflow.com/a/44109830/1860868
  • name 上的索引是一列,{"first_name", "last_name"} 上的索引是跨多列的复合索引。
  • 你能详细解释一下吗?

标签: android android-room android-architecture-components


【解决方案1】:

答案有点晚了。但希望对某人有所帮助。

Q1:indices@Index有什么用?

Indices: 可以包含表上的索引列表。而 @Index 用于定义索引

例如:

@Entity(indices = {
    @Index("FirstIndex"),@Index(value="last_name",unique = true),
    @Index("SecondIndex"),@Index(value="first_name", unique = true)
})

如您所见,我在此示例中定义了两个以逗号分隔的索引。这里“FirstIndex”和“SecondIndex”是索引的名称。如果我没有定义索引的名称(正如您在示例中引用的那样),那么 Room 会将其设置为由 '' 连接并以“index${tableName}”为前缀的列列表.因此,如果您有一个名称为“Foo”且索引为 {“bar”、“baz”} 的表,则生成的索引名称将为“index_Foo_bar_baz”。

Q2:@Index("name")@Index(value = {"last_name", "address"})有什么区别?

@index("name") //syntax to give name of index.
@index(value=last_name", "address") //Syntax to define, which column(s) need to be indexed

【讨论】:

  • 这不是真的:“如果我没有定义索引的名称(如您在示例中引用的那样),那么 Room 会将其视为空字符串。”根据文档:如果未设置,Room 会将其设置为由“_”连接并以“index_${tableName}”为前缀的列列表。因此,如果您有一个名为“Foo”且索引为 {“bar”、“baz”} 的表,则生成的索引名称将为“index_Foo_bar_baz” 来源:developer.android.com/reference/androidx/room
  • @FerB。我已经更新了答案。谢谢指正。
【解决方案2】:

索引是添加索引的过程,用于快速定位数据,而不必在每次查询或访问数据库表时搜索数据库表中的每一行。 Room 支持使用 indices 属性对某些字段或字段组进行索引以加快查询速度。您可以查看以下链接以获取更多知识。

https://proandroiddev.com/exploring-room-architecture-component-the-extras-cf3f0259ceed

【讨论】:

  • 投了反对票,因为没有回答 2 个 OP 问题并解释了一个未回答的问题。每个人都知道索引是什么以及用于什么,任何网络搜索都会提供足够的材料来了解它,但是 OP 问题非常具体,通过简单的搜索无法找到它们。我来到这里寻找相同问题的答案,但没有找到。
猜你喜欢
  • 2011-05-04
  • 1970-01-01
  • 1970-01-01
  • 2011-09-15
  • 2010-09-11
  • 1970-01-01
  • 1970-01-01
  • 2013-02-20
  • 1970-01-01
相关资源
最近更新 更多