Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamically create index with mongoid

I have a job that create new fields to my document, I want, at the end of this job, to create indexes to this fields. I tried

Model.index("field"=>-1)

and also

Mongoid::Sessions.default[:rating_prediction].ensureIndex

Without success

Is this possible?

like image 624
Chen Kinnrot Avatar asked Mar 21 '14 21:03

Chen Kinnrot


People also ask

How do I create indexes in Mongoid?

You can check out this page for Mongoid v3.x if you haven't upgraded yet. You can define indexes on documents using the index macro. Provide the key for the index along with a direction. For additional options, supply them in a second options hash parameter. You can define indexes on embedded document fields as well.

What is the default name of an index in MongoDB?

MongoDB indexes use a B-tree data structure. 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.

What is a multikey Index in MongoDB?

If you index a field that holds an array value, MongoDB creates separate index entries for every element of the array. These multikey indexes allow queries to select documents that contain arrays by matching on element or elements of the arrays.

What is collation and indexing in MongoDB?

The collation applies only to the index keys with string values. The collation applies to the indexed keys whose values are string. For queries or sort operations on the indexed keys that uses the same collation rules, MongoDB can use the index. For details, see Collation and Index Use. New in version 4.2.


1 Answers

Saying Model.index(:field => -1), more or less, just registers the existence of the index with Model, it doesn't actually create an index. You're looking for create_indexes:

- (true) create_indexes

Send the actual index creation comments to the MongoDB driver

So you'd want to say:

Model.index(field: -1)
Model.create_indexes

You can also create them directly through Moped by calling create on the collection's indexes:

Mongoid::Sessions.default[:models].indexes.create(field: -1)
Model.collection.indexes.create(field: 1)
# or in newer versions:
Model.collection.indexes.create_one(field: 1)

Mongoid::Sessions has been renamed to Mongoid::Clients in newer versions so you might need to say:

Mongoid::Clients.default[:models].indexes.create(field: 1)
Model.collection.indexes.create(field: 1)
# or in even newer versions:
Model.collection.indexes.create_one(field: 1)

Thanks to js_ and mltsy for noting these changes.

like image 109
mu is too short Avatar answered Oct 13 '22 16:10

mu is too short