// MongoIndexes returns the indexes to apply to the clouldimagemetadata collection.
// We return an index that expires records containing a created-at field after 5 minutes.
431786
func MongoIndexes() []mgo.Index {
	return []mgo.Index{{
		Key:         []string{"expire-at"},
		ExpireAfter: expiryTime,
		Sparse:      true,
	}}
}
1013712
func InitModels() {
	index := mgo.Index{
		Key:      []string{"username"},
		Unique:   true,
		DropDups: true,
	}

	db.EnsureIndex(mongoUsersCollectionName, index)

	// Removes users without valid 2 factor authentication after 3 days
	automaticUserExpiration := mgo.Index{
		Key:         []string{"expire"},
		ExpireAfter: time.Second * 3600 * 24 * 3,
		Background:  true,
	}
	db.EnsureIndex(mongoUsersCollectionName, automaticUserExpiration)

	avatarIndex := mgo.Index{
		Key:      []string{"hash"},
		Unique:   true,
		DropDups: true,
	}
	db.EnsureIndex(mongoAvatarFileCollectionName, avatarIndex)

	emailIndex := mgo.Index{
		Key: []string{"emailaddresses.emailaddress"},
	}
	db.EnsureIndex(mongoUsersCollectionName, emailIndex)
}
459281
func (session *Session) CreateIndexes(bean interface{}) error {
	v := rValue(bean)
	session.Statement.setRefValue(v)

	defer session.resetStatement()
	if session.IsAutoClose {
		defer session.Close()
	}

	sqls := session.Statement.genIndexSQL()
	for _, sqlStr := range sqls {
		_, err := session.exec(sqlStr)
		if err != nil {
			return err
		}
	}
	return nil
}
1068037
func (ix *Index) indexReadyBlobs(ctx context.Context) {
	defer ix.reindexWg.Done()
	ix.RLock()
	// For tests
	if ix.oooDisabled {
		ix.RUnlock()
		return
	}
	ix.RUnlock()
	failed := make(map[blob.Ref]bool)
	for {
		ix.Lock()
		if len(ix.readyReindex) == 0 {
			ix.Unlock()
			return
		}
		var br blob.Ref
		for br = range ix.readyReindex {
			break
		}
		delete(ix.readyReindex, br)
		ix.Unlock()
		if err := ix.indexBlob(ctx, br); err != nil {
			log.Printf("out-of-order indexBlob(%v) = %v", br, err)
			failed[br] = true
		}
	}
	ix.Lock()
	defer ix.Unlock()
	for br := range failed {
		ix.readyReindex[br] = true
	}
}
600335
func (ta *Table) UniqueIndexes() int {
	unique := 0
	for _, idx := range ta.Indexes {
		if idx.Unique {
			unique++
		}
	}
	return unique
}
50356
func (s *ReindexService) SourceIndex(index string) *ReindexService {
	if s.source == nil {
		s.source = NewReindexSource()
	}
	s.source = s.source.Index(index)
	return s
}
421302
func (o *Object) AddToIndex(indexName string, indexValue string) {
	if o.Indexes == nil {
		o.Indexes = make(map[string][]string)
	}
	if o.Indexes[indexName] == nil {
		o.Indexes[indexName] = make([]string, 1)
		o.Indexes[indexName][0] = indexValue
	} else {
		o.Indexes[indexName] = append(o.Indexes[indexName], indexValue)
	}
}
610493
func (session *Session) DropIndexes(bean interface{}) error {
	if session.isAutoClose {
		defer session.Close()
	}

	return session.dropIndexes(bean)
}
1154631
func OpenShardedIndex(path string) (ShardedIndex, error) {
	var meta shardedIndexMetadata
	var err error
	if err = readJSON(shardedIndexMetadataPath(path), &meta); err != nil {
		return nil, err
	}

	s := &shardedIndex{
		indices: make([]bleve.Index, meta.NumShards),
	}
	for i := 0; i < meta.NumShards; i++ {
		s.indices[i], err = bleve.Open(childIndexerPath(path, i))
		if err != nil {
			return nil, err
		}
	}
	s.bleveIndex = bleve.NewIndexAlias(s.indices...)
	return s, nil
}
300207
func (col *Col) Index(idxPath []string) (err error) {
	col.db.schemaLock.Lock()
	defer col.db.schemaLock.Unlock()
	idxName := strings.Join(idxPath, INDEX_PATH_SEP)
	if _, exists := col.indexPaths[idxName]; exists {
		return fmt.Errorf("Path %v is already indexed", idxPath)
	}
	col.indexPaths[idxName] = idxPath
	idxDir := path.Join(col.db.path, col.name, idxName)
	if err = os.MkdirAll(idxDir, 0700); err != nil {
		return err
	}
	for i := 0; i < col.db.numParts; i++ {
		if col.hts[i][idxName], err = col.db.Config.OpenHashTable(path.Join(idxDir, strconv.Itoa(i))); err != nil {
			return err
		}
	}
	// Put all documents on the new index
	col.forEachDoc(func(id int, doc []byte) (moveOn bool) {
		var docObj map[string]interface{}
		if err := json.Unmarshal(doc, &docObj); err != nil {
			// Skip corrupted document
			return true
		}
		for _, idxVal := range GetIn(docObj, idxPath) {
			if idxVal != nil {
				hashKey := StrHash(fmt.Sprint(idxVal))
				col.hts[hashKey%col.db.numParts][idxName].Put(hashKey, id)
			}
		}
		return true
	}, false)
	return
}
1073324
func (c *DefaultIndexingChain) fillStoredFields(docId int) (err error) {
	for err == nil && c.lastStoredDocId < docId {
		err = c.startStoredFields()
		if err == nil {
			err = c.finishStoredFields()
		}
	}
	return
}
1341895
func (self *Collection) GetFieldByIndex(index int) (Field, bool) {
	if index == self.IdentityFieldIndex {
		return Field{
			Name:     self.GetIdentityFieldName(),
			Type:     self.IdentityFieldType,
			Index:    self.IdentityFieldIndex,
			Identity: true,
			Key:      true,
			Required: true,
		}, true
	} else {
		for _, field := range self.Fields {
			if field.Index == index {
				return field, true
			}
		}
	}

	return Field{}, false
}
966749
func PgTableIndexes(db XODB, schema string, table string) ([]*Index, error) {
	var err error

	// sql query
	const sqlstr = `SELECT ` +
		`DISTINCT ic.relname, ` + // ::varchar AS index_name
		`i.indisunique, ` + // ::boolean AS is_unique
		`i.indisprimary, ` + // ::boolean AS is_primary
		`0, ` + // ::integer AS seq_no
		`'', ` + // ::varchar AS origin
		`false ` + // ::boolean AS is_partial
		`FROM pg_index i ` +
		`JOIN ONLY pg_class c ON c.oid = i.indrelid ` +
		`JOIN ONLY pg_namespace n ON n.oid = c.relnamespace ` +
		`JOIN ONLY pg_class ic ON ic.oid = i.indexrelid ` +
		`WHERE i.indkey <> '0' AND n.nspname = $1 AND c.relname = $2`

	// run query
	XOLog(sqlstr, schema, table)
	q, err := db.Query(sqlstr, schema, table)
	if err != nil {
		return nil, err
	}
	defer q.Close()

	// load results
	res := []*Index{}
	for q.Next() {
		i := Index{}

		// scan
		err = q.Scan(&i.IndexName, &i.IsUnique, &i.IsPrimary, &i.SeqNo, &i.Origin, &i.IsPartial)
		if err != nil {
			return nil, err
		}

		res = append(res, &i)
	}

	return res, nil
}
126423
func (o *SortOption) Indexes() []int {
	var ret []int
	for _, x := range o.orderByList {
		ret = append(ret, x.Index)
	}
	return ret
}
153817
func (c *Client) ListIndexes(opts ...interface{}) (res ListIndexesRes, err error) {
	path := c.path("/indexes")
	err = c.transport.Request(&res, http.MethodGet, path, nil, call.Read, opts...)
	return
}
547977
func (ind *Indices) extractIndexes(indexIds []string) IndexMetadataSlice {
	result := make(IndexMetadataSlice, 0, len(ind.Indexes))
	if len(indexIds) == 0 {
		// No ids specified so return everything.
		for _, metadata := range ind.Indexes {
			result = append(result, metadata)
		}
	} else {
		// Return metadata for just the specified ids.
		for _, id := range indexIds {
			if metadata, ok := ind.Indexes[id]; ok {
				result = append(result, metadata)
			}
		}
	}
	return result
}
350019
func (b *Backend) createMongoIndexes(database string) error {

	tasksCollection := b.client.Database(database).Collection("tasks")

	expireIn := int32(b.GetConfig().ResultsExpireIn)

	_, err := tasksCollection.Indexes().CreateMany(context.Background(), []mongo.IndexModel{
		{
			Keys:    bson.M{"state": 1},
			Options: options.Index().SetBackground(true).SetExpireAfterSeconds(expireIn),
		},
		mongo.IndexModel{
			Keys:    bson.M{"lock": 1},
			Options: options.Index().SetBackground(true).SetExpireAfterSeconds(expireIn),
		},
	})
	if err != nil {
		return err
	}

	return err
}