MongoDB index

As we all know, creating an index can greatly improve query efficiency. As a nosql database, MongoDB also supports the performance improvement of queries through indexes. Without an index, MongoDB must perform a scan of the entire collection to find documents that match the query. MongoDB can use indexes to limit the number of documents that must be retrieved, provided an appropriate index exists for a query.

An index is a very special data structure that stores a small subset of the dataset in a collection in a form that is easy to retrieve. The index stores the value of a specified field or a collection of specified fields, and is sorted by the value of the field. Sorting of indexed entities supports high-quality equality matching and range-related query operations. In addition to this, MongoDB can return sorted results by using the order in the index. MongoDB provides collection-level index creation and usage.

default _id index

By default, MongoDB creates a unique index for the _id field when the collection is created. This is done to prevent clients from inserting multiple _id documents with the same value. And the index cannot be destroyed once created.

create index

In native Java drivers, indexes can be created using the db.collection.crateIndex() method. The format is as follows:

 

db.collection.createIndex( <key and index type specification>, <options> )
 This method will only create an index if the type specification corresponding to the key does not exist. MongoDB indexes use the B-tree data structure. 1. Let's first understand <options>: In the official documentation , <options> is a document object that contains a series of choices that control index creation. List of <options> options common to all index types (since version 3.0, the dropDups option is no longer available):
parameter Types of Parameter Description
background boolean Optional parameter, specify true to create indexes in the background without blocking other database activities. The default value is false.
unique boolean Optional parameter, specify true to create a unique index, the collection will not accept the insertion of documents whose index keys (keys) match a value in the index. Default is false.
name string

Optional parameter, the name of the index. If not specified, MongoDB will automatically generate an index name with an underscore concatenated by the index key and sort (0 or 1).

When specifying an index name, its complete namespace (<database name>.<collection name>.$<index name>) cannot exceed 128 bytes.

partialFilterExpression document

Optional parameter. If specified, the index will refer to the copy that matches the filter expression.

A filter expression must contain:

  • Equal expressions, i.e. (filed:value) indicate or, use the $eq operator
  • $exists
  • $gt, $gte, $lt, $lte
  • $type
  • $and, only on top-level fields
sparse boolean Optional parameter, sparse index. Specify true and the index will refer to documents for the specified field. Such an index has less space overhead, but behaves differently in different scenarios, especially sorting. Default is false.
expireAfterSeconds integer Optional parameter, specifying a value in seconds, which controls how long the document exists in the collection.
storageEngine document

Optional parameter, new in 3.0. Format

{ <storage-engine-name>: <options> }, specifies the storage engine.

   

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

Options for full-text indexing:

parameter Types of Parameter Description
weights document Optional parameter, a document object containing filed, weight pairs. weight is an integer from 1 to 99999, and its value indicates the degree of association and importance of a file and other index files. This value can be specified for some or all index fields. Default 1. Verbose
default_language string Optional parameter, default is English. The language determines the stopword list and the rules for stemmers and tokenizers.
language_override string Optional parameter, defaults to language. In a Filed of a document in a collection, you can specify a different language when creating an index.
textIndexVersion integer Optional parameter, the version of the full-text index.

 

2. Types of Indexes

MongoDB provides many different index types to support specific types of data and queries. Only three types of single index, compound index, and full-text index are discussed here.

single index

In addition to MongoDB's custom _id index, the database also supports user-defined incrementing and decrementing indexes on a single Filed of a document. A single index supports queries on index fields. For example, suppose there is a collection of records with the following structure:

{
  "_id": ObjectId("570c04a4ad233577f97dc459"),
  "score": 1034,
  "location": { state: "NY", city: "New York" }
}

We create an incremental index on the score:

db.records.createIndex( { score: 1 } )
 The index created in this way supports queries on the score field, such as:
db.records.find( { score: 2 } )
db.records.find( { score: { $gt: 10 } } )
  A composite index is an index created on multiple fields. The ordering of Fields in a compound index is significant. For example, if a composite index consists of { userid: 1, score: -1 }, the index will first be sorted by userid in ascending order, and within the same userid, again by descending score. In addition, the ordering of the keys of an index directly determines the ordering operations supported by the index. for example;

 

Suppose there is a collection events, and its document contains two fields username and date, create the following index:

db.events.createIndex( { "username" : 1, "date" : -1 } )
 As such, only the following two query sort operations will be supported:

 

 

db.events.find().sort( { username: 1, date: -1 } )
db.events.find().sort( { username: -1, date: 1 } )
 However, the following operations will not be supported:

 

 

db.events.find().sort( { username: 1, date: 1 } )
 One caveat: If a conforming index is created, MongoDB can use the index to support queries on index prefixes. The index prefix refers to the subset of the Filed list that creates the index starting from the first Filed, such as creating an index of the following form:

 

 

db.collection.crateIndex({ "item": 1, "location": 1, "stock": 1 });
 Then, the index only supports the following three kinds of queries:

 

db.collection.find({ item: "item1", location: "location1", stock: "stock1" });
db.collection.find({ item: "item2", location: "location2"});
db.collection.find({ item: "item3"});

And only supports fully-incrementing and fully-decrementing sort operations on one or more of these three Fileds.

full text index

Starting with MongoDB 3.2, MongoDB has a third version of full-text indexing. MongoDB provides full-text indexing to support text searches on an entire row. The full-text index can be any Filed whose value is a String or an array of Strings. A collection can have at most one full-text index.

Create a full-text index:

 To create a full-text index, use the db.collection.createIndex() method. To index a Filed that contains a String or an array of Strings, indicate the FIIED and denote it as "text" in the indexed document. as follows:

db.reviews.createIndex( { comments: "text" } )

 Likewise, full-text indexes can be created on multiple FIleds. Create a full-text index on subject and comment as follows:

 

db.reviews.createIndex(
   {
     subject: "text",
     comments: "text"
   }
 )

When you need to drop a full-text index, use db.collection.dropIndex("MyTextIndex"), where MyTextIndex is the name of the index.

Limited specific gravity (Weights)

For a full-text index, the weight of an indexed field indicates the significance of a field in relation to other fields. For each index Filed in the document,

 

References: https://docs.mongodb.com/manual/indexes/

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326853702&siteId=291194637