In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-03-26 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/01 Report--
This article Xiaobian for you to introduce in detail "MongoDB index type how to achieve", the content is detailed, the steps are clear, the details are handled properly, I hope this "MongoDB index type how to achieve" article can help you solve your doubts, following the editor's ideas slowly in-depth, together to learn new knowledge.
MongoDB 4.2 officially supports the following index types:
Single field index
Composite index
Multi-key index
Text indexing
2dsphere index
2d index
GeoHaystack index
Hash indexing
A single field index creates an ascending index handong1:PRIMARY > db.test.getIndexes () on a single field [{"v": 2, "key": {"_ id": 1}, "name": "_ id_" "ns": "db6.test"}]
Add an ascending index to the field id
Handong1:PRIMARY > db.test.createIndex ({"id": 1}) {"createdCollectionAutomatically": false, "numIndexesBefore": 1, "numIndexesAfter": 2, "ok": 1, "$clusterTime": {"clusterTime": Timestamp (1621322378, 1), "signature": {"hash": BinData (0 "AAAAAAAAAAAAAAAAAAAAAAAAAAA="), "keyId": NumberLong (0)}}, "operationTime": Timestamp (1621322378, 1)} handong1:PRIMARY > db.test.getIndexes () [{"v": 2, "key": {"_ id": 1} "name": "_ id_", "ns": "db6.test"}, {"v": 2, "key": {"id": 1}, "name": "id_1" "ns": "db6.test"}] handong1:PRIMARY > db.test.find ({"id": 100}) {"_ id": ObjectId ("60a35d061f183b1d8f092114"), "id": 100, "name": "handong", "ziliao": {"name": "handong", "age": 25, "hobby": "mongodb"}}
The above query can use the newly created single-field index.
Create an index handong1:PRIMARY > db.test.createIndex ({"ziliao.name": 1}) {"createdCollectionAutomatically": false, "numIndexesBefore": 2, "numIndexesAfter": 3, "ok": 1, "$clusterTime": {"clusterTime": Timestamp (1621323677, 2) on the embedded field "signature": {"hash": BinData (0, "AAAAAAAAAAAAAAAAAAAAAAAAAAA="), "keyId": NumberLong (0)}, "operationTime": Timestamp (1621323677, 2)}
The new index available for the following query.
Db.test.find ({"ziliao.name": "handong"}) create an index on the embedded document handong1:PRIMARY > db.test.createIndex ({ziliao:1}) {"createdCollectionAutomatically": false, "numIndexesBefore": 3, "numIndexesAfter": 4, "ok": 1, "$clusterTime": {"clusterTime": Timestamp (1621324059, 2) "signature": {"hash": BinData (0, "AAAAAAAAAAAAAAAAAAAAAAAAAAA="), "keyId": NumberLong (0)}, "operationTime": Timestamp (1621324059, 2)}
The following query can use the newly created index.
Db.test.find ({ziliao: {"name": "handong", "age": 25, "hobby": "mongodb"}}) compound index
Create a composite index
Db.user.createIndex ({"product_id": 1, "type":-1})
The new composite index can be used in the following query
Db.user.find ({"product_id": "e5a35cfc70364d2092b8f5d14b1a3217", "type": 0}) multi-key index
When an index is created based on an array, MongoDB is automatically created as a multi-key index without deliberate assignment.
Multi-key indexes can also be created based on embedded documents.
The calculation of the boundary value of a multi-key index depends on specific rules.
View the document:
Handong1:PRIMARY > db.score.find () {"_ id": ObjectId ("60a32d7f1f183b1d8f0920ad"), "name": "dandan", "age": 30, "score": [{"english": 90, "math": 99, "physics": 88}], "is_del": false} {"_ id": ObjectId ("60a32d8b1f183b1d8f0920ae"), "name": "dandan", "age": 30 "score": [99, 98, 97, 96], "is_del": false} {"_ id": ObjectId ("60a32d9a1f183b1d8f0920af"), "name": "dandan", "age": 30, "score": [100,100,100,100], "is_del": false} {"_ id": ObjectId ("60a32e8c1f183b1d8f0920b0"), "name": "dandan", "age": 30 "score": [{"english": 70, "math": 99, "physics": 88}], "is_del": false} {"_ id": ObjectId ("60a37b141f183b1d8f0aa751"), "name": "dandan", "age": 30, "score": [96,95]} {"_ id": ObjectId ("60a37b1d1f183b1d8f0aa752"), "name": "dandan", "age": 30 "score": [96,95,94]} {"_ id": ObjectId ("60a37b221f183b1d8f0aa753"), "name": "dandan", "age": 30, "score": [96,95,94,93]}
Create a score field multi-key index:
Db.score.createIndex ("score": 1) handong1:PRIMARY > db.score.find ({"score": [96,95]}) {"_ id": ObjectId ("60a37b141f183b1d8f0aa751"), "name": "dandan", "age": 30, "score": [96,95]}
View the execution plan:
Handong1:PRIMARY > db.score.find ({"score": [96,95]}). Explain () {"queryPlanner": {"plannerVersion": 1, "namespace": "db6.score", "indexFilterSet": false "parsedQuery": {"score": {"$eq": [96 95]}, "queryHash": "8D76FC59", "planCacheKey": "E2B03CA1" "winningPlan": {"stage": "FETCH", "filter": {"score": {"$eq": [96 95]}, "inputStage": {"stage": "IXSCAN" "keyPattern": {"score": 1}, "indexName": "score_1", "isMultiKey": true "multiKeyPaths": {"score": ["score"]} "isUnique": false, "isSparse": false, "isPartial": false, "indexVersion": 2, "direction": "forward" "indexBounds": {"score": ["[96.0,96.0]", "[96.0,95.0], [96.0,96.0] 95.0]] "]}}," rejectedPlans ": []}," serverInfo ": {" host ":" mongo3 " "port": 27017, "version": "4.2.12", "gitVersion": "5593fd8e33b60c75802edab304e23998fa0ce8a5"}, "ok": 1, "$clusterTime": {"clusterTime": Timestamp (1621326912, 1) "signature": {"hash": BinData (0, "AAAAAAAAAAAAAAAAAAAAAAAAAAA="), "keyId": NumberLong (0)}, "operationTime": Timestamp (1621326912, 1)}
You can see that the newly created multi-key index has been used.
Text indexing
provides text indexing to support text search queries on the contents of strings. A text index can contain any field whose value is a string or an array of string elements
Db.user.createIndex ({"sku_attributes": "text"}) db.user.find ({$text: {$search: "Test"}})
View the execution plan:
Handong1:PRIMARY > db.user.find ({$text: {$search: "Test"}). Explain () {"queryPlanner": {"plannerVersion": 1, "namespace": "db6.user", "indexFilterSet": false "parsedQuery": {"$text": {"$search": "Test", "$language": "english", "$caseSensitive": false "$diacriticSensitive": false}}, "queryHash": "83098EE1", "planCacheKey": "7E2D582B", "winningPlan": {"stage": "TEXT" "indexPrefix": {}, "indexName": "sku_attributes_text" "parsedTextQuery": {"terms": ["Test"], "negatedTerms": [] "phrases": [], "negatedPhrases": []}, "textIndexVersion": 3, "inputStage": {"stage": "TEXT_MATCH" "inputStage": {"stage": "FETCH", "inputStage": {"stage": "OR" "inputStage": {"stage": "IXSCAN" "keyPattern": {"_ fts": "text" "_ ftsx": 1}, "indexName": "sku_attributes_text" "isMultiKey": true, "isUnique": false, "isSparse": false "isPartial": false, "indexVersion": 2, "direction": "backward" "indexBounds": {} }}} "rejectedPlans": []}, "serverInfo": {"host": "mongo3", "port": 27017, "version": "4.2.12", "gitVersion": "5593fd8e33b60c75802edab304e23998fa0ce8a5"}, "ok": 1 "$clusterTime": {"clusterTime": Timestamp (1621328543, 1), "signature": {"hash": BinData (0, "AAAAAAAAAAAAAAAAAAAAAAAAAAA="), "keyId": NumberLong (0)}}, "operationTime": Timestamp (1621328543, 1)}
You can see that the data containing the test keyword can be found through the text index.
* * Note: * * you can create a composite text index according to your needs.
2dsphere index creation test data db.places.insert ({loc: {type: "Point", coordinates: [116.291226, 39.981198]}, name: "Firearms Camp Bridge", category: "Firearms Camp Bridge"}) db.places.insert ({loc: {type: "Point", coordinates: [116.281452, 39.914226]}, name: "Wukesong" Category: "Wukesong"}) db.places.insert ({loc: {type: "Point", coordinates: [116.378038, 39.851467]}, name: "Corner Gate West", category: "Corner Gate West"}) db.places.insert ({loc: {type: "Point", coordinates: [116.467833, 39.881581]}, name: "Panjiayuan" Category: "Panjiayuan"}) db.places.insert ({loc: {type: "Point", coordinates: [116.468264, 39.914766]}, name: "International Trade", category: "International Trade"}) db.places.insert ({loc: {type: "Point", coordinates: [116.46618, 39.960213]}, name: "Sanyuan Bridge" Category: "three Yuan Bridge"}) db.places.insert ({loc: {type: "Point", coordinates: [116.400064, 40.007827]}, name: "Olympic Forest Park", category: "Olympic Forest Park"}) add 2dsphere index db.places.createIndex ({loc: "2dsphere"}) db.places.createIndex ({loc: "2dsphere") Category:-1, name: 1}) query points in polygons using 2dsphere index
Phoenix Ridge
[116.098234,40.110569]
Tiananmen
[116.405239,39.913839]
Sihui Bridge
[116.494351,39.912068]
Wangjing
[116.494494,40.004594]
Handong1:PRIMARY > db.places.find ({loc:.. {$geoWithin:.. {$geometry:.. {type: "Polygon",... Coordinates: [[... [116.098234,40.110569],... [116.405239,39.913839],... [116.494351,39.912068] ... [116.494494,40.004594],... [116.098234,40.110569]... ]]... }) {"_ id": ObjectId ("60a4c950d4211a77d22bf7f8"), "loc": {"type": "Point", "coordinates": [116.400064, 40.007827]}, "name": "Olympic Forest Park", "category": "Olympic Forest Park"} {"_ id": ObjectId ("60a4c94fd4211a77d22bf7f7") "loc": {"type": "Point", "coordinates": [116.46618, 39.960213]}, "name": "Sanyuan Bridge", "category": "Sanyuan Bridge"} {"_ id": ObjectId ("60a4c94fd4211a77d22bf7f6"), "loc": {"type": "Point", "coordinates": [116.468264, 39.914766]}, "name": "International Trade" "category": "ITC"}
You can see that all the points contained in the set in the specified quadrilateral are listed.
Use the 2dsphere index to query the point handong1:PRIMARY > db.places.find ({loc:.. {$geoWithin:.. {$centerSphere:. [116.439518, 39.954751], 2max 3963.2]. }) {"_ id": ObjectId ("60a4c94fd4211a77d22bf7f7"), "loc": {"type": "Point", "coordinates": [116.46618, 39.960213]}, "name": "Sanyuan Bridge", "category": "Sanyuan Bridge"}
Returns all coordinates within 2 miles with a radius of longitude 116.439518 E and latitude 39.954751 N. The example converts a distance of 2 miles into radians by dividing by the Earth's approximate equatorial radius of 3963.2 miles.
2d index
Use a 2d index in the following cases:
Your database has legacy coordinate pairs from MongoDB 2.2 or earlier.
You do not intend to store any location data as a GeoJSON object.
Hash indexing
To create an hashed index, specify hashed as the value of the index key, as shown in the following example:
Handong1:PRIMARY > db.test.createIndex ({"_ id": "hashed"}) {"createdCollectionAutomatically": false, "numIndexesBefore": 4, "numIndexesAfter": 5, "ok": 1, "$clusterTime": {"clusterTime": Timestamp (1621419338, 1), "signature": {"hash": BinData (0) "AAAAAAAAAAAAAAAAAAAAAAAAAAA="), "keyId": NumberLong (0)}, "operationTime": Timestamp (1621419338, 1)}
Matters needing attention
MongoDB supports hashed indexes for any single field. The hashing function collapses the embedded document and calculates the hash value of the entire value, but does not support multiple keys (I. e. Array) index.
You cannot create a composite index with hashed index fields, nor can you specify a unique constraint hashed; on the index, but you can hashed create indexes and ascending / descending (that is, non-hash) indexes on the same field: MongoDB will use scalar indexes for range queries.
Read here, this article "how to achieve the MongoDB index type" article has been introduced, want to master the knowledge of this article also need to practice and use to understand, if you want to know more about the article, welcome to follow the industry information channel.
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.