El contenido no se encuentra disponible en el idioma seleccionado. Estamos trabajando continuamente para agregar más idiomas. Gracias por su apoyo.

Compute
Elastic Cloud Server
Huawei Cloud Flexus
Bare Metal Server
Auto Scaling
Image Management Service
Dedicated Host
FunctionGraph
Cloud Phone Host
Huawei Cloud EulerOS
Networking
Virtual Private Cloud
Elastic IP
Elastic Load Balance
NAT Gateway
Direct Connect
Virtual Private Network
VPC Endpoint
Cloud Connect
Enterprise Router
Enterprise Switch
Global Accelerator
Management & Governance
Cloud Eye
Identity and Access Management
Cloud Trace Service
Resource Formation Service
Tag Management Service
Log Tank Service
Config
OneAccess
Resource Access Manager
Simple Message Notification
Application Performance Management
Application Operations Management
Organizations
Optimization Advisor
IAM Identity Center
Cloud Operations Center
Resource Governance Center
Migration
Server Migration Service
Object Storage Migration Service
Cloud Data Migration
Migration Center
Cloud Ecosystem
KooGallery
Partner Center
User Support
My Account
Billing Center
Cost Center
Resource Center
Enterprise Management
Service Tickets
HUAWEI CLOUD (International) FAQs
ICP Filing
Support Plans
My Credentials
Customer Operation Capabilities
Partner Support Plans
Professional Services
Analytics
MapReduce Service
Data Lake Insight
CloudTable Service
Cloud Search Service
Data Lake Visualization
Data Ingestion Service
GaussDB(DWS)
DataArts Studio
Data Lake Factory
DataArts Lake Formation
IoT
IoT Device Access
Others
Product Pricing Details
System Permissions
Console Quick Start
Common FAQs
Instructions for Associating with a HUAWEI CLOUD Partner
Message Center
Security & Compliance
Security Technologies and Applications
Web Application Firewall
Host Security Service
Cloud Firewall
SecMaster
Anti-DDoS Service
Data Encryption Workshop
Database Security Service
Cloud Bastion Host
Data Security Center
Cloud Certificate Manager
Edge Security
Situation Awareness
Managed Threat Detection
Blockchain
Blockchain Service
Web3 Node Engine Service
Media Services
Media Processing Center
Video On Demand
Live
SparkRTC
MetaStudio
Storage
Object Storage Service
Elastic Volume Service
Cloud Backup and Recovery
Storage Disaster Recovery Service
Scalable File Service Turbo
Scalable File Service
Volume Backup Service
Cloud Server Backup Service
Data Express Service
Dedicated Distributed Storage Service
Containers
Cloud Container Engine
SoftWare Repository for Container
Application Service Mesh
Ubiquitous Cloud Native Service
Cloud Container Instance
Databases
Relational Database Service
Document Database Service
Data Admin Service
Data Replication Service
GeminiDB
GaussDB
Distributed Database Middleware
Database and Application Migration UGO
TaurusDB
Middleware
Distributed Cache Service
API Gateway
Distributed Message Service for Kafka
Distributed Message Service for RabbitMQ
Distributed Message Service for RocketMQ
Cloud Service Engine
Multi-Site High Availability Service
EventGrid
Dedicated Cloud
Dedicated Computing Cluster
Business Applications
Workspace
ROMA Connect
Message & SMS
Domain Name Service
Edge Data Center Management
Meeting
AI
Face Recognition Service
Graph Engine Service
Content Moderation
Image Recognition
Optical Character Recognition
ModelArts
ImageSearch
Conversational Bot Service
Speech Interaction Service
Huawei HiLens
Video Intelligent Analysis Service
Developer Tools
SDK Developer Guide
API Request Signing Guide
Terraform
Koo Command Line Interface
Content Delivery & Edge Computing
Content Delivery Network
Intelligent EdgeFabric
CloudPond
Intelligent EdgeCloud
Solutions
SAP Cloud
High Performance Computing
Developer Services
ServiceStage
CodeArts
CodeArts PerfTest
CodeArts Req
CodeArts Pipeline
CodeArts Build
CodeArts Deploy
CodeArts Artifact
CodeArts TestPlan
CodeArts Check
CodeArts Repo
Cloud Application Engine
MacroVerse aPaaS
KooMessage
KooPhone
KooDrive

Creating and Managing Indexes

Updated on 2024-05-13 GMT+08:00

DDS uses indexes to improve query efficiency. If there is no index, DDS must scan each document in a collection to select the documents that match the query statement. If a query has an appropriate index, DDS can use the index to limit the number of documents it must examine.

  • For details about the rules for creating indexes, see Index.
  • For details about the rules of the write/update and delete commands, see Write/Update and Delete.

Indexes

Index

Description

Default index

DDS creates a unique index on the _id field during the creation of a collection. A unique index ensures that the indexed fields do not store duplicate values. Do not delete the index from the _id field.

In a sharded cluster, if you do not use the _id field as the shard key, your application needs to ensure that the value in the _id field is unique to prevent errors. This is usually done by using the standard automatically generated ObjectId.

Single field index

In addition to the _id index defined by DDS, DDS also supports the creation of user-defined ascending/descending indexes on a single field of a document.

For single-field indexing and sort operations, the sort order (ascending or descending) of index keys is not important because DDS can traverse the index from any direction.

Compound indexes

DDS also supports compound indexes where a single index field contains references to multiple fields.

The order of the fields listed in a compound index is important. For example, if there is a compound index {userid: 1, score: -1}, the index is first sorted by userid and then sorted by score within each userid value.

The sort order (ascending or descending) of the index keys determines whether the index supports sort operations.

Multikey index

DDS uses a multikey index to index the content stored in arrays. If the index contains fields with array values, DDS creates a separate index entry for each element of the array. These multikey indexes allow queries to select documents that contain an array by matching one or more elements of the array. DDS automatically determines whether to create a multi-key index. If the index field contains an array value, you do not need to explicitly specify the multikey type.

Index Name

The default name for an index is the concatenation of the indexed keys and each key's direction in the index (i.e. 1 or -1) using underscores as a separator. For example, an index created on { item : 1, quantity: -1 } has the name item_1_quantity_-1.

You can create indexes with a custom name, such as one that is more human-readable than the default. For example, consider an application that frequently queries the products collection to populate data on existing inventory. The following createIndex() method creates an index on item and quantity named query for inventory:

db.products.createIndex( { item: 1, quantity: -1 } , { name: "query for inventory" })

You can use the db.collection.getIndexes() method to view the index name. Once an index is created, you cannot rename it. Instead, you must drop and recreate the index with the new name.

DDS provides many different index types to support specific types of data and queries.

Creating an Index

  1. Run the following command to create an index:

    db.collection.createIndex(keys, options)

    • key is the index field to be created. The value 1 indicates that the index is created in ascending order, and the value -1 indicates that the index is created in descending order.
    • options receives optional parameters. The following table lists common optional parameters.

      Parameter

      Type

      Description

      background

      Boolean

      The default value is false.

      The index creation process blocks other database operations. You can specify the background mode to create indexes.

      unique

      Boolean

      The default value is false.

      Whether the created index is unique. If this parameter is set to true, a unique index is created.

      name

      string

      Index name. If this parameter is not specified, MongoDB generates an index name by joining the index field name and sorting order.

      expireAfterSeconds

      integer

      TTL value in seconds.

  2. Create an index.

    • Single field index

      db.user.createIndex({"name": 1})

      The preceding statement creates a single-field index for the name field, which can accelerate various query requests on the name field. This is the most common index type. The ID index created by default is also of this type. {"name": 1} means that indexed items are sorted in ascending order. You can also use {"name": -1} to sort index items in descending order. For a single-field index, the effect of ascending order is the same as that of descending order.

    • Composite index

      A composite index is an upgraded version of a single sub-index. It creates an index for multiple fields. Documents are sorted by the first field, documents with the same first field are sorted by the second field, and so on.

      db.user.createIndex({"name": 1, "age": 1} )

    • Multikey index
      • If an index field is an array, the created index is called a multikey index.
      • A multikey index creates an index for each element of an array.

      For example, if a habit field (array) is added to the user collection to describe interests and hobbies, the multikey index of the habit field can be used to query people with the same interests and hobbies.

      {"name" : "jack", "age" : 19, habit: ["football, runnning"]} //This is a piece of user information in the person table.

      db.user.createIndex( {"habit": 1} ) //Multi-key indexes are automatically created.

      db.user.find( {"habit": "football"} ) //Query people with the same interests and hobbies.

  3. View the collection index.

    db.user.getIndexes()

  4. Deletes all indexes from a collection.

    db.user.dropIndexes()

  5. Deletes a specified index from a collection. Run the following command to delete the name index from the user collection:

    db.user.dropIndex({"name": 1})

Precaution

In addition to various types of indexes, DDS allows you to customize some special attributes for indexes.

  • Unique index: Ensure that the values of the fields corresponding to an index are different. For example, the _id index is a unique index.
  • TTL index: You can specify the expiration time of a document based on a time field. The document expires after the specified time or at a specified time point.
  • Partial index: An index is created only for documents that meet a specific condition.
  • Sparse index: Indexes are created only for documents that have index fields, which can be considered as a special case of partial indexes.

Utilizamos cookies para mejorar nuestro sitio y tu experiencia. Al continuar navegando en nuestro sitio, tú aceptas nuestra política de cookies. Descubre más

Feedback

Feedback

Feedback

0/500

Selected Content

Submit selected content with the feedback