Performs a secondary index query.
500376
def get_index(self, bucket, index, startkey, endkey=None,
                  return_terms=None, max_results=None, continuation=None,
                  timeout=None, term_regex=None):
        
        if term_regex and not self.index_term_regex():
            raise NotImplementedError("Secondary index term_regex is not "
                                      "supported on %s" %
                                      self.server_version.vstring)

        if timeout == 'infinity':
            timeout = 0

        params = {'return_terms': return_terms, 'max_results': max_results,
                  'continuation': continuation, 'timeout': timeout,
                  'term_regex': term_regex}
        bucket_type = self._get_bucket_type(bucket.bucket_type)
        url = self.index_path(bucket.name, index, startkey, endkey,
                              bucket_type=bucket_type, **params)
        status, headers, body = self._request('GET', url)
        self.check_http_code(status, [200])
        json_data = json.loads(bytes_to_str(body))
        if return_terms and u'results' in json_data:
            results = []
            for result in json_data[u'results'][:]:
                term, key = list(result.items())[0]
                results.append((decode_index_value(index, term), key),)
        else:
            results = json_data[u'keys'][:]

        if max_results and u'continuation' in json_data:
            return (results, json_data[u'continuation'])
        else:
            return (results, None)
833640
def iter_query_indexes(self):
        
        if self._table.range_key is None:
            range_key = None
        else:
            range_key = self._table.range_key.name
        yield QueryIndex("TABLE", True, self._table.hash_key.name, range_key)
        for index in self._table.indexes:
            yield QueryIndex.from_table_index(self._table, index)
        for index in self._table.global_indexes:
            yield QueryIndex.from_table_index(self._table, index)
147102
def get_index_by_name(self, db_name, tbl_name, index_name):
    
    self.send_get_index_by_name(db_name, tbl_name, index_name)
    return self.recv_get_index_by_name()
1157661
private static void updatePartialIndex(IndexScanPlanNode scan) {
        if (scan.getPredicate() == null && scan.getPartialIndexPredicate() != null) {
            if (scan.isForSortOrderOnly()) {
                scan.setPredicate(Collections.singletonList(scan.getPartialIndexPredicate()));
            }
            scan.setForPartialIndexOnly();
        }
    }
1336756
public Index<SecondaryTable<T>> getOrCreateIndex()
   {
      List<Node> nodeList = childNode.get("index");
      if (nodeList != null &&  nodeList.size() > 0)
      {
         return new IndexImpl<SecondaryTable<T>>(this, "index", childNode, nodeList.get(0));
      }
      return createIndex();
   }
1184569
private void indexArrayStore(int e, int i)
    {
        if (valueIndexStore.length < e)
        {
            int oldLength = valueIndexStore.length;
            valueIndexStore = Arrays.copyOf(valueIndexStore, e + 2);
            Arrays.fill(valueIndexStore, oldLength, valueIndexStore.length, -1);
        }
        valueIndexStore[e] = i;
    }
343479
public void addSubMetricQuery(final String metric_query, 
                                final int sub_query_index,
                                final int param_index) {
    if (metric_query == null || metric_query.isEmpty()) {
      throw new IllegalArgumentException("Metric query cannot be null or empty");
    }
    if (sub_query_index < 0) {
      throw new IllegalArgumentException("Sub query index must be 0 or greater");
    }
    if (param_index < 0) {
      throw new IllegalArgumentException("Parameter index must be 0 or greater");
    }
    if (sub_metric_queries == null) {
      sub_metric_queries = Maps.newHashMap();
    }
    sub_metric_queries.put(sub_query_index, metric_query);
    parameter_index.put(param_index, Parameter.METRIC_QUERY);
  }
1142451
public function index()
    {
        $index = $this->getIndexName();

        $this->assertTrue(
            $this->table->hasIndex($index), "The {$this->name} column is not indexed."
        );

        $this->assertTrue(
            $this->table->getIndex($index)->isSimpleIndex(), "The {$this->name} column is not a simple index."
        );
    }
313712
function index(req, res, next) {
  var nextPage
    , prevPage
    , page
    , links = {}
    , link = req.url + '?page=';

  db.users.all({page: req.query.page, limit: req.query.limit}, function(err, result) {
    if(err) { return next(err); }

    page = result.page;
    nextPage = result.count - (result.limit + result.offset) > 0;
    prevPage = page > 1;

    if(nextPage) links.next = link + (page + 1);
    if(prevPage) links.prev = link + (page - 1);
    if(Object.keys(links).length) res.links(links);

    res.json({
      links: links,
      page: page,
      count: result.count,
      users: result.rows,
      next: nextPage,
      prev: prevPage
    });

  });
}
726539
public JSONObject multipleQueries(List<IndexQuery> queries) throws AlgoliaException {
    return multipleQueries(queries, "none", RequestOptions.empty);
  }
506016
function(queryRunner, options) {
    options = options || {};
    this.queryParser = new QueryParser(options.paramValueRegEx);
    var indexNameBuilder = options.indexNameBuilder || new DefaultIndexNameBuilder();
    this.queryBuilder = new EsQueryBuilder(indexNameBuilder, {
        defaults: options.queryDefaults
    });
    this.queryRunner = queryRunner;
}
1226945
public Iterable<DContact> queryByPrimaryCustomIndex(Object parent, java.lang.String primaryCustomIndex) {
    return queryByField(parent, DContactMapper.Field.PRIMARYCUSTOMINDEX.getFieldName(), primaryCustomIndex);
  }
88338
private int otherIndex(int i) {
        IDoubleBondStereochemistry element = (IDoubleBondStereochemistry) queryElements[i];
        return queryMap.get(element.getStereoBond().getOther(query.getAtom(i)));
    }
668440
public JSONObject multipleQueries(List<IndexQuery> queries, RequestOptions requestOptions) throws AlgoliaException {
    return multipleQueries(queries, "none", requestOptions);
  }
300402
def fetch_search_document(self, *, index):
        """"""
        assert self.pk, "Object must have a primary key before being indexed."
        client = get_client()
        return client.get(index=index, doc_type=self.search_doc_type, id=self.pk)
396060
def update_index(index):
    """"""
    logger.info("Updating search index: '%s'", index)
    client = get_client()
    responses = []
    for model in get_index_models(index):
        logger.info("Updating search index model: '%s'", model.search_doc_type)
        objects = model.objects.get_search_queryset(index).iterator()
        actions = bulk_actions(objects, index=index, action="index")
        response = helpers.bulk(client, actions, chunk_size=get_setting("chunk_size"))
        responses.append(response)
    return responses
859795
void buildIndex(double desiredSpeed, boolean discardDuplicates, boolean verifyOnly)
        throws RepositoryException
    {
        final MergeSortBuffer buffer;
        final Comparator c;

        final Log log = LogFactory.getLog(IndexedStorage.class);

        final Query<S> masterQuery;
        {
            // Need to explicitly order master query by primary key in order
            // for fetchAfter to work correctly in case corrupt records are
            // encountered.
            masterQuery = mMasterStorage.query()
                .orderBy(naturalOrdering(mMasterStorage.getStorableType()));
        }

        // Quick check to see if any records exist in master.
        {
            Transaction txn = mRepository.enterTopTransaction(IsolationLevel.READ_COMMITTED);
            try {
                if (!masterQuery.exists()) {
                    if (mIndexEntryStorage.query().exists()) {
                        txn.exit();
                        mIndexEntryStorage.truncate();
                    }
                    return;
                }
            } finally {
                txn.exit();
            }
        }

        // Enter top transaction with isolation level of none to make sure
        // preload operation does not run in a long nested transaction.
        Transaction txn = mRepository.enterTopTransaction(IsolationLevel.NONE);
        try {
            Cursor<S> cursor = masterQuery.fetch();
            try {
                if (log.isInfoEnabled()) {
                    StringBuilder b = new StringBuilder();
                    b.append("Preparing index on ");
                    b.append(mMasterStorage.getStorableType().getName());
                    b.append(": ");
                    try {
                        mIndex.appendTo(b);
                    } catch (java.io.IOException e) {
                        // Not gonna happen.
                    }
                    log.info(b.toString());
                }

                // Preload and sort all index entries for improved performance.

                buffer = new MergeSortBuffer(mIndexEntryStorage, null, BUILD_SORT_BUFFER_SIZE);
                c = getComparator();
                buffer.prepare(c);

                long nextReportTime = System.currentTimeMillis() + BUILD_INFO_DELAY_MILLIS;

                // These variables are used when corrupt records are encountered.
                S lastUserStorable = null;
                int skippedCount = 0;

                while (cursor.hasNext()) {
                    S userStorable;
                    try {
                        userStorable = cursor.next();
                        skippedCount = 0;
                    } catch (CorruptEncodingException e) {
                        log.warn("Omitting corrupt record from index: " + e.toString());

                        // Exception forces cursor to close. Close again to be sure.
                        cursor.close();

                        if (lastUserStorable == null) {
                            cursor = masterQuery.fetch();
                        } else {
                            cursor = masterQuery.fetchAfter(lastUserStorable);
                        }

                        cursor.skipNext(++skippedCount);
                        continue;
                    }

                    buffer.add(makeIndexEntry(userStorable));

                    if (log.isInfoEnabled()) {
                        long now = System.currentTimeMillis();
                        if (now >= nextReportTime) {
                            log.info("Prepared " + buffer.size() + " index entries");
                            nextReportTime = now + BUILD_INFO_DELAY_MILLIS;
                        }
                    }

                    lastUserStorable = userStorable;
                }

                // No need to commit transaction because no changes should have been made.
            } finally {
                cursor.close();
            }
        } finally {
            txn.exit();
        }

        // This is not expected to take long, since MergeSortBuffer sorts as
        // needed. This just finishes off what was not written to a file.
        buffer.sort();

        if (isUnique()) {
            // If index is unique, scan buffer and check for duplicates
            // _before_ inserting index entries. If there are duplicates,
            // fail, since unique index cannot be built.

            log.info("Verifying index");

            Object last = null;
            for (Object obj : buffer) {
                if (last != null && c.compare(last, obj) == 0) {
                    if (discardDuplicates) {
                        log.warn("Unique index contains duplicates; skipping: "
                                 + this + ", " + last + " == " + obj);
                    } else {
                        buffer.close();
                        throw new UniqueConstraintException
                            ("Cannot build unique index because duplicates exist: "
                             + this + ", " + last + " == " + obj);
                    }
                }
                last = obj;
            }
        }

        if (verifyOnly) {
            log.info("Verification complete");
            buffer.close();
            return;
        }

        final int bufferSize = buffer.size();

        if (log.isInfoEnabled()) {
            log.info("Begin build of " + bufferSize + " index entries");
        }

        // Need this index entry query for deleting bogus entries.
        final Query indexEntryQuery = mIndexEntryStorage.query()
            .orderBy(naturalOrdering(mIndexEntryStorage.getStorableType()));

        Throttle throttle = desiredSpeed < 1.0 ? new Throttle(BUILD_THROTTLE_WINDOW) : null;

        long totalInserted = 0;
        long totalUpdated = 0;
        long totalDeleted = 0;
        long totalProgress = 0;

        txn = enterBuildTxn();
        try {
            Cursor<? extends Storable> indexEntryCursor = indexEntryQuery.fetch();
            Storable existingIndexEntry = null;

            if (!indexEntryCursor.hasNext()) {
                indexEntryCursor.close();
                // Don't try opening again.
                indexEntryCursor = null;
            }

            boolean retry = false;
            Storable indexEntry = null;
            Storable lastIndexEntry = null;

            long nextReportTime = System.currentTimeMillis() + BUILD_INFO_DELAY_MILLIS;

            Iterator it = buffer.iterator();
            bufferIterate: while (true) {
                if (!retry) {
                    Object obj;
                    if (it.hasNext()) {
                        obj = it.next();
                    } else if (indexEntryCursor != null && indexEntryCursor.hasNext()) {
                        obj = null;
                    } else {
                        break;
                    }

                    indexEntry = (Storable) obj;
                }

                try {
                    if (indexEntry != null) {
                        if (indexEntry.tryInsert()) {
                            totalInserted++;
                        } else if (!discardDuplicates) {
                            // Couldn't insert because an index entry already exists.
                            Storable existing = indexEntry.copy();
                            boolean doUpdate = false;
                            if (!existing.tryLoad()) {
                                doUpdate = true;
                            } else if (!existing.equalProperties(indexEntry)) {
                                // If only the version differs, leave existing entry alone.
                                indexEntry.copyVersionProperty(existing);
                                doUpdate = !existing.equalProperties(indexEntry);
                            }
                            if (doUpdate) {
                                indexEntry.tryDelete();
                                indexEntry.tryInsert();
                                totalUpdated++;
                            }
                        }
                    }

                    if (indexEntryCursor != null) while (true) {
                        if (existingIndexEntry == null) {
                            if (indexEntryCursor.hasNext()) {
                                existingIndexEntry = indexEntryCursor.next();
                            } else {
                                indexEntryCursor.close();
                                // Don't try opening again.
                                indexEntryCursor = null;
                                break;
                            }
                        }

                        int compare = c.compare(existingIndexEntry, indexEntry);

                        if (compare == 0) {
                            // Existing entry cursor matches so allow cursor to advance.
                            existingIndexEntry = null;
                            break;
                        } else if (compare > 0) {
                            // Existing index entry is ahead so check later.
                            break;
                        } else {
                            // Existing index entry might be bogus. Check again
                            // in case master record changed.
                            doDelete: {
                                S master = mMasterStorage.prepare();
                                copyToMasterPrimaryKey(existingIndexEntry, master);
                                if (master.tryLoad()) {
                                    Storable temp = makeIndexEntry(master);
                                    existingIndexEntry.copyVersionProperty(temp);
                                    if (existingIndexEntry.equalProperties(temp)) {
                                        break doDelete;
                                    }
                                }

                                existingIndexEntry.tryDelete();
                                totalDeleted++;

                                if (totalDeleted % BUILD_BATCH_SIZE == 0) {
                                    txn.commit();
                                    txn.exit();

                                    nextReportTime = logProgress
                                        (nextReportTime, log, totalProgress, bufferSize,
                                         totalInserted, totalUpdated, totalDeleted);

                                    txn = enterBuildTxn();

                                    indexEntryCursor.close();
                                    indexEntryCursor = indexEntryQuery
                                        .fetchAfter(existingIndexEntry);

                                    if (!indexEntryCursor.hasNext()) {
                                        indexEntryCursor.close();
                                        // Don't try opening again.
                                        indexEntryCursor = null;
                                        break;
                                    }
                                }
                            }

                            existingIndexEntry = null;

                            throttle(throttle, desiredSpeed);
                        }
                    }

                    if (indexEntry != null) {
                        totalProgress++;
                    }

                    lastIndexEntry = indexEntry;
                    retry = false;
                } catch (RepositoryException e) {
                    if (e instanceof FetchTimeoutException ||
                        e instanceof FetchDeadlockException ||
                        e instanceof PersistTimeoutException ||
                        e instanceof PersistDeadlockException)
                    {
                        log.warn("Lock conflict during index repair; will retry: " +
                                 indexEntry + ", " + e);
                        // This re-uses the last index entry to repair and forces
                        // the current transaction to commit.
                        retry = true;
                    } else {
                        throw e;
                    }
                }

                if (retry || (totalProgress % BUILD_BATCH_SIZE == 0)) {
                    txn.commit();
                    txn.exit();

                    nextReportTime = logProgress(nextReportTime, log, totalProgress, bufferSize,
                                                 totalInserted, totalUpdated, totalDeleted);

                    txn = enterBuildTxn();

                    if (indexEntryCursor != null) {
                        indexEntryCursor.close();
                        existingIndexEntry = null;

                        if (indexEntry == null || lastIndexEntry == null) {
                            indexEntryCursor = indexEntryQuery.fetch();
                        } else if (!retry) {
                            indexEntryCursor = indexEntryQuery.fetchAfter(indexEntry);
                        } else {
                            // Re-fetch starting at the same spot.
                            indexEntryCursor = indexEntryQuery.fetchAfter(lastIndexEntry);
                        }
                    }
                }

                throttle(throttle, desiredSpeed);
            }

            txn.commit();
        } finally {
            txn.exit();
            buffer.close();
        }

        if (log.isInfoEnabled()) {
            log.info("Finished building " + totalProgress + " index entries " +
                     progressSubMessgage(totalInserted, totalUpdated, totalDeleted));
        }
    }