简体   繁体   中英

mongodb — trying to construct a compound index based on the query

I'm a little bit confused as to what would be a good index (or indices?) for the query I'm trying to employ. This query isn't unique, but it's pretty much the gist of how my queries look like right now. I've replaced values with placeholders, so they might not make a lot of sense. There's also the need to sort at the end.

 { oId: 1, status: { '$in': [ 'STATUS1', 'STATUS2' ] }, '$and': [ { '$or': [ { '$or': [ { prov: 'P1', '$or': [ { tags: { '$in': [ 'tag1' ] } } ] }, { prov: 'P2', '$or': [ { tags: { '$in': [ 'tag1' ] } } ] }, { prov: 'P3', '$or': [ { tags: { '$in': [ 'tag1' ] } } ] }, { prov: 'P4', '$or': [ { tags: { '$in': [ 'tag1' ] } } ] } ] }, { '$or': [ { prov: 'P1', login: { '$in': [ 'login1' ] } }, { prov: 'P2', login: { '$in': [ 'login2' ] } }, { prov: 'P3', login: { '$in': [ 'login1' ] } }, { prov: 'P3', login: { '$in': [ 'login3' ] } } ] }, { '$or': [ { prov: 'P3', group: { '$in': [ 'group1' ] } } ] }, { '$or': [ { prov: 'P2', locationId: { '$in': [ '1', '2' ] } } ] } ] }, { '$or': [ { prov: 'P1', '$or': [ { group: 'group2' }, { login: 'login5' } ] }, { prov: 'P2', '$or': [ { group: 'group3' }, { login: 'login3' } ] }, { prov: 'P3', '$or': [ { login: 'login3' } ] }, { prov: 'P4', '$or': [ { login: 'login3' } ] } ] } ] }, {sort: {createdAt: -1}} 

An example document looks like this:

{
    oId: 1,
    login: 'login1',
    locationId: 2,
    prov: 'P1',
    status: 'STATUS1',
    group: 'group1',
    createdAt: <DateTime>,
    tags: ['tag1', 'tag2']
}

I understand the principle of how compound indexes should be formed on a small number of fields, yet it seems like I don't really understand how I am to accomplish it in my own case.

Any input is appreciated, of course.

I would create an index something like this.

{ oId: 1, status: -1, prov: -1, login: -1, locationId: -1, createdAt: -1, group: -1, tags: -1 }

so as far as a complex index goes the only part that matters on a compound index is the first option. so anything that uses oId and any combination and order of the rest of the index. Will use the index. The only other part that would change over a simple index is that the sort order cannot change with a compound index.

good luck.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM