首页 > 解决方案 > 为什么必须对 Spring Boot 应用程序中的用户角色属性进行索引?

问题描述

我正在尝试使用 Spring Boot 将 Employee Pojo 存储在 Mongo db 上,我发现它已在 Internet 中的一个站点上被索引。将其编入索引的需要和原因是什么?

import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;
import org.springframework.data.mongodb.core.index.IndexDirection;
import org.springframework.data.mongodb.core.index.Indexed;

@Document(collection = "role")
public class Role {

    @Id
    private String id;
    @Indexed(unique = true, direction = IndexDirection.DESCENDING, dropDups = true)

    private String role;

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getRole() {
        return role;
    }

    public void setRole(String role) {
        this.role = role;
    }

}

标签: springmongodbhibernatespring-boot

解决方案


来自 mongo 文档:https ://docs.mongodb.com/manual/indexes/

Indexes support the efficient execution of queries in MongoDB. Without indexes,
MongoDB must perform a collection scan, i.e. scan every document in a collection,
to select those documents that match the query statement. If an appropriate index
exists for a query, MongoDB can use the index to limit the number of documents it
must inspect.

不需要索引role。但是 - 如果您使用roleas 条件查询您的员工集合,它将加快查询执行速度。

要索引的字段取决于您的用例/您访问数据的方式。


推荐阅读