AMashenkov commented on a change in pull request #9118:
URL: https://github.com/apache/ignite/pull/9118#discussion_r696414843



##########
File path: 
modules/core/src/main/java/org/apache/ignite/internal/cache/query/index/IndexQueryProcessor.java
##########
@@ -0,0 +1,456 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.ignite.internal.cache.query.index;
+
+import java.lang.reflect.Array;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.Comparator;
+import java.util.List;
+import java.util.NoSuchElementException;
+import java.util.PriorityQueue;
+import org.apache.ignite.IgniteCheckedException;
+import org.apache.ignite.IgniteException;
+import org.apache.ignite.cache.query.IndexQuery;
+import org.apache.ignite.cache.query.IndexQueryCriterion;
+import org.apache.ignite.internal.cache.query.RangeIndexQueryCriterion;
+import org.apache.ignite.internal.cache.query.index.sorted.IndexKeyDefinition;
+import 
org.apache.ignite.internal.cache.query.index.sorted.IndexKeyTypeSettings;
+import org.apache.ignite.internal.cache.query.index.sorted.IndexRow;
+import org.apache.ignite.internal.cache.query.index.sorted.IndexRowComparator;
+import org.apache.ignite.internal.cache.query.index.sorted.IndexSearchRowImpl;
+import 
org.apache.ignite.internal.cache.query.index.sorted.InlineIndexRowHandler;
+import 
org.apache.ignite.internal.cache.query.index.sorted.SortedIndexDefinition;
+import 
org.apache.ignite.internal.cache.query.index.sorted.inline.IndexQueryContext;
+import org.apache.ignite.internal.cache.query.index.sorted.inline.InlineIndex;
+import org.apache.ignite.internal.cache.query.index.sorted.keys.IndexKey;
+import 
org.apache.ignite.internal.cache.query.index.sorted.keys.IndexKeyFactory;
+import org.apache.ignite.internal.processors.cache.CacheObjectContext;
+import org.apache.ignite.internal.processors.cache.CacheObjectUtils;
+import org.apache.ignite.internal.processors.cache.GridCacheContext;
+import org.apache.ignite.internal.processors.cache.query.IndexQueryDesc;
+import org.apache.ignite.internal.processors.query.QueryUtils;
+import org.apache.ignite.internal.util.GridCloseableIteratorAdapter;
+import org.apache.ignite.internal.util.lang.GridCloseableIterator;
+import org.apache.ignite.internal.util.lang.GridCursor;
+import org.apache.ignite.internal.util.typedef.internal.U;
+import org.apache.ignite.lang.IgniteBiTuple;
+
+import static org.apache.ignite.internal.cache.query.index.SortOrder.DESC;
+
+/**
+ * Processor of {@link IndexQuery}.
+ */
+public class IndexQueryProcessor {
+    /** */
+    private final IndexProcessor idxProc;
+
+    /** */
+    public IndexQueryProcessor(IndexProcessor idxProc) {
+        this.idxProc = idxProc;
+    }
+
+    /** Run query on local node. */
+    public <K, V> GridCloseableIterator<IgniteBiTuple<K, V>> queryLocal(
+        GridCacheContext<K, V> cctx, IndexQueryDesc idxQryDesc, 
IndexQueryContext qryCtx, boolean keepBinary)
+        throws IgniteCheckedException {
+
+        Index idx = index(cctx, idxQryDesc);
+
+        GridCursor<IndexRow> cursor = query(cctx, idx, idxQryDesc.criteria(), 
qryCtx);
+
+        // Map IndexRow to Cache Key-Value pair.
+        return new GridCloseableIteratorAdapter<IgniteBiTuple<K, V>>() {
+            private IndexRow currVal;
+
+            private final CacheObjectContext coctx = cctx.cacheObjectContext();
+
+            /** {@inheritDoc} */
+            @Override protected boolean onHasNext() throws 
IgniteCheckedException {
+                if (currVal != null)
+                    return true;
+
+                if (!cursor.next())
+                    return false;
+
+                currVal = cursor.get();
+
+                return true;
+            }
+
+            /** {@inheritDoc} */
+            @Override protected IgniteBiTuple<K, V> onNext() {
+                if (currVal == null)
+                    if (!hasNext())
+                        throw new NoSuchElementException();
+
+                IndexRow row = currVal;
+
+                currVal = null;
+
+                K k = (K) CacheObjectUtils.unwrapBinaryIfNeeded(coctx, 
row.cacheDataRow().key(), keepBinary, false);
+                V v = (V) CacheObjectUtils.unwrapBinaryIfNeeded(coctx, 
row.cacheDataRow().value(), keepBinary, false);
+
+                return new IgniteBiTuple<>(k, v);
+            }
+        };
+    }
+
+    /** Get index to run query by specified description. */
+    private Index index(GridCacheContext cctx, IndexQueryDesc idxQryDesc) 
throws IgniteCheckedException {
+        Class<?> valCls = idxQryDesc.valCls() != null ? loadValClass(cctx, 
idxQryDesc.valCls()) : null;
+
+        String tableName = cctx.kernalContext().query().tableName(cctx.name(), 
valCls);
+
+        if (tableName == null)
+            throw failIndexQuery("No table found: " + idxQryDesc.valCls(), 
cctx, idxQryDesc);
+
+        if (idxQryDesc.idxName() != null) {
+            Index idx = indexByName(cctx, idxQryDesc, tableName);
+
+            if (idx == null)
+                throw failIndexQuery("No index found: " + 
idxQryDesc.idxName(), cctx, idxQryDesc);
+
+            return idx;
+        }
+
+        Index idx = indexByCriteria(cctx, idxQryDesc, tableName);
+
+        if (idx == null)
+            throw failIndexQuery("No index matches query", cctx, idxQryDesc);
+
+        return idx;
+    }
+
+    /** Get index by name, or return {@code null}. */
+    private Index indexByName(GridCacheContext cctx, IndexQueryDesc 
idxQryDesc, String tableName) throws IgniteCheckedException {
+        String name = idxQryDesc.idxName();
+
+        if (!QueryUtils.PRIMARY_KEY_INDEX.equals(name))
+            name = name.toUpperCase();
+
+        String schema = cctx.kernalContext().query().schemaName(cctx);
+
+        IndexName idxName = new IndexName(cctx.name(), schema, tableName, 
name);
+
+        Index idx = idxProc.index(idxName);
+
+        if (idx == null)
+            return null;
+
+        if (!checkIndex(idxProc.indexDefinition(idx.id()), 
idxQryDesc.criteria()))
+            throw failIndexQuery("Index " + idxQryDesc.idxName() + " doesn't 
match query", cctx, idxQryDesc);
+
+        return idx;
+    }
+
+    /** */
+    private IgniteCheckedException failIndexQuery(String msg, GridCacheContext 
cctx, IndexQueryDesc desc) {
+        return new IgniteCheckedException(
+            "Failed to parse IndexQuery. " + msg + ". Cache=" + cctx.name() + 
"; Query=" + desc);
+    }
+
+    /**
+     * Get index by list of fields to query, or return {@code null}.
+     *
+     * Note, it tries to find best index match: count of index fields should 
equal to count of index criteria fields.
+     */
+    private Index indexByCriteria(GridCacheContext cctx, IndexQueryDesc 
idxQryDesc, String tableName) {
+        Collection<Index> idxs = idxProc.indexes(cctx);
+
+        for (Index i: idxs) {
+            IndexDefinition idxDef = idxProc.indexDefinition(i.id());
+
+            if (!tableName.equals(idxDef.idxName().tableName()))
+                continue;
+
+            if (checkIndex(idxDef, idxQryDesc.criteria()))
+                return i;
+        }
+
+        return null;
+    }
+
+    /** Checks that specified index matches index query criteria. */
+    private boolean checkIndex(IndexDefinition idxDef, 
List<IndexQueryCriterion> criteria) {
+        if (criteria.size() > idxDef.indexKeyDefinitions().size())
+            return false;
+
+        for (int i = 0; i < criteria.size(); i++) {
+            if 
(!idxDef.indexKeyDefinitions().get(i).name().equalsIgnoreCase(criteria.get(i).field()))
+                return false;
+        }
+
+        return true;
+    }
+
+    /** */
+    private Class<?> loadValClass(GridCacheContext cctx, String valClsName) 
throws IgniteCheckedException {
+        try {
+            ClassLoader clsLdr = 
U.resolveClassLoader(cctx.kernalContext().config());
+
+            return clsLdr.loadClass(valClsName);
+        }
+        catch (ClassNotFoundException e) {
+            throw new IgniteCheckedException("No cache serves class: " + 
valClsName);
+        }
+    }
+
+    /**
+     * Runs an index query.
+     *
+     * @return Result cursor over index segments.
+     */
+    private GridCursor<IndexRow> query(GridCacheContext cctx, Index idx, 
List<IndexQueryCriterion> criteria, IndexQueryContext qryCtx)
+        throws IgniteCheckedException {
+
+        int segmentsCnt = cctx.isPartitioned() ? 
cctx.config().getQueryParallelism() : 1;
+
+        if (segmentsCnt == 1)
+            return query(0, idx, criteria, qryCtx);
+
+        final GridCursor<IndexRow>[] segments = new GridCursor[segmentsCnt];

Review comment:
       ```suggestion
           final GridCursor<IndexRow>[] segmentCursor = new 
GridCursor[segmentsCnt];
   ```




-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]


Reply via email to