001/*
002 * Licensed to the Apache Software Foundation (ASF) under one
003 * or more contributor license agreements.  See the NOTICE file
004 * distributed with this work for additional information
005 * regarding copyright ownership.  The ASF licenses this file
006 * to you under the Apache License, Version 2.0 (the
007 * "License"); you may not use this file except in compliance
008 * with the License.  You may obtain a copy of the License at
009 *
010 *     http://www.apache.org/licenses/LICENSE-2.0
011 *
012 * Unless required by applicable law or agreed to in writing, software
013 * distributed under the License is distributed on an "AS IS" BASIS,
014 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
015 * See the License for the specific language governing permissions and
016 * limitations under the License.
017 */
018package org.apache.hadoop.hbase.client;
019
020import java.io.IOException;
021import java.util.ArrayList;
022import java.util.HashMap;
023import java.util.List;
024import java.util.Map;
025import java.util.NavigableSet;
026import java.util.TreeMap;
027import java.util.TreeSet;
028import java.util.stream.Collectors;
029import org.apache.hadoop.hbase.HConstants;
030import org.apache.hadoop.hbase.client.metrics.ScanMetrics;
031import org.apache.hadoop.hbase.filter.Filter;
032import org.apache.hadoop.hbase.filter.IncompatibleFilterException;
033import org.apache.hadoop.hbase.io.TimeRange;
034import org.apache.hadoop.hbase.security.access.Permission;
035import org.apache.hadoop.hbase.security.visibility.Authorizations;
036import org.apache.hadoop.hbase.util.Bytes;
037import org.apache.yetus.audience.InterfaceAudience;
038import org.slf4j.Logger;
039import org.slf4j.LoggerFactory;
040
041import org.apache.hadoop.hbase.shaded.protobuf.ProtobufUtil;
042
043/**
044 * Used to perform Scan operations.
045 * <p>
046 * All operations are identical to {@link Get} with the exception of instantiation. Rather than
047 * specifying a single row, an optional startRow and stopRow may be defined. If rows are not
048 * specified, the Scanner will iterate over all rows.
049 * <p>
050 * To get all columns from all rows of a Table, create an instance with no constraints; use the
051 * {@link #Scan()} constructor. To constrain the scan to specific column families, call
052 * {@link #addFamily(byte[]) addFamily} for each family to retrieve on your Scan instance.
053 * <p>
054 * To get specific columns, call {@link #addColumn(byte[], byte[]) addColumn} for each column to
055 * retrieve.
056 * <p>
057 * To only retrieve columns within a specific range of version timestamps, call
058 * {@link #setTimeRange(long, long) setTimeRange}.
059 * <p>
060 * To only retrieve columns with a specific timestamp, call {@link #setTimestamp(long) setTimestamp}
061 * .
062 * <p>
063 * To limit the number of versions of each column to be returned, call {@link #setMaxVersions(int)
064 * setMaxVersions}.
065 * <p>
066 * To limit the maximum number of values returned for each call to next(), call
067 * {@link #setBatch(int) setBatch}.
068 * <p>
069 * To add a filter, call {@link #setFilter(org.apache.hadoop.hbase.filter.Filter) setFilter}.
070 * <p>
071 * For small scan, it is deprecated in 2.0.0. Now we have a {@link #setLimit(int)} method in Scan
072 * object which is used to tell RS how many rows we want. If the rows return reaches the limit, the
073 * RS will close the RegionScanner automatically. And we will also fetch data when openScanner in
074 * the new implementation, this means we can also finish a scan operation in one rpc call. And we
075 * have also introduced a {@link #setReadType(ReadType)} method. You can use this method to tell RS
076 * to use pread explicitly.
077 * <p>
078 * Expert: To explicitly disable server-side block caching for this scan, execute
079 * {@link #setCacheBlocks(boolean)}.
080 * <p>
081 * <em>Note:</em> Usage alters Scan instances. Internally, attributes are updated as the Scan runs
082 * and if enabled, metrics accumulate in the Scan instance. Be aware this is the case when you go to
083 * clone a Scan instance or if you go to reuse a created Scan instance; safer is create a Scan
084 * instance per usage.
085 */
086@InterfaceAudience.Public
087public class Scan extends Query {
088  private static final Logger LOG = LoggerFactory.getLogger(Scan.class);
089
090  private static final String RAW_ATTR = "_raw_";
091
092  private byte[] startRow = HConstants.EMPTY_START_ROW;
093  private boolean includeStartRow = true;
094  private byte[] stopRow = HConstants.EMPTY_END_ROW;
095  private boolean includeStopRow = false;
096  private int maxVersions = 1;
097  private int batch = -1;
098
099  /**
100   * Partial {@link Result}s are {@link Result}s must be combined to form a complete {@link Result}.
101   * The {@link Result}s had to be returned in fragments (i.e. as partials) because the size of the
102   * cells in the row exceeded max result size on the server. Typically partial results will be
103   * combined client side into complete results before being delivered to the caller. However, if
104   * this flag is set, the caller is indicating that they do not mind seeing partial results (i.e.
105   * they understand that the results returned from the Scanner may only represent part of a
106   * particular row). In such a case, any attempt to combine the partials into a complete result on
107   * the client side will be skipped, and the caller will be able to see the exact results returned
108   * from the server.
109   */
110  private boolean allowPartialResults = false;
111
112  private int storeLimit = -1;
113  private int storeOffset = 0;
114
115  /**
116   * @deprecated since 1.0.0. Use {@link #setScanMetricsEnabled(boolean)}
117   */
118  // Make private or remove.
119  @Deprecated
120  static public final String SCAN_ATTRIBUTES_METRICS_ENABLE = "scan.attributes.metrics.enable";
121
122  /**
123   * Use {@link #getScanMetrics()}
124   */
125  // Make this private or remove.
126  @Deprecated
127  static public final String SCAN_ATTRIBUTES_METRICS_DATA = "scan.attributes.metrics.data";
128
129  // If an application wants to use multiple scans over different tables each scan must
130  // define this attribute with the appropriate table name by calling
131  // scan.setAttribute(Scan.SCAN_ATTRIBUTES_TABLE_NAME, Bytes.toBytes(tableName))
132  static public final String SCAN_ATTRIBUTES_TABLE_NAME = "scan.attributes.table.name";
133  static private final String SCAN_ATTRIBUTES_METRICS_BY_REGION_ENABLE =
134    "scan.attributes.metrics.byregion.enable";
135
136  /**
137   * -1 means no caching specified and the value of {@link HConstants#HBASE_CLIENT_SCANNER_CACHING}
138   * (default to {@link HConstants#DEFAULT_HBASE_CLIENT_SCANNER_CACHING}) will be used
139   */
140  private int caching = -1;
141  private long maxResultSize = -1;
142  private boolean cacheBlocks = true;
143  private boolean reversed = false;
144  private TimeRange tr = TimeRange.allTime();
145  private Map<byte[], NavigableSet<byte[]>> familyMap =
146    new TreeMap<byte[], NavigableSet<byte[]>>(Bytes.BYTES_COMPARATOR);
147  private Boolean asyncPrefetch = null;
148
149  /**
150   * Parameter name for client scanner sync/async prefetch toggle. When using async scanner,
151   * prefetching data from the server is done at the background. The parameter currently won't have
152   * any effect in the case that the user has set Scan#setSmall or Scan#setReversed
153   */
154  public static final String HBASE_CLIENT_SCANNER_ASYNC_PREFETCH =
155    "hbase.client.scanner.async.prefetch";
156
157  /**
158   * Default value of {@link #HBASE_CLIENT_SCANNER_ASYNC_PREFETCH}.
159   */
160  public static final boolean DEFAULT_HBASE_CLIENT_SCANNER_ASYNC_PREFETCH = false;
161
162  /**
163   * Set it true for small scan to get better performance Small scan should use pread and big scan
164   * can use seek + read seek + read is fast but can cause two problem (1) resource contention (2)
165   * cause too much network io [89-fb] Using pread for non-compaction read request
166   * https://issues.apache.org/jira/browse/HBASE-7266 On the other hand, if setting it true, we
167   * would do openScanner,next,closeScanner in one RPC call. It means the better performance for
168   * small scan. [HBASE-9488]. Generally, if the scan range is within one data block(64KB), it could
169   * be considered as a small scan.
170   */
171  private boolean small = false;
172
173  /**
174   * The mvcc read point to use when open a scanner. Remember to clear it after switching regions as
175   * the mvcc is only valid within region scope.
176   */
177  private long mvccReadPoint = -1L;
178
179  /**
180   * The number of rows we want for this scan. We will terminate the scan if the number of return
181   * rows reaches this value.
182   */
183  private int limit = -1;
184
185  /**
186   * Control whether to use pread at server side.
187   */
188  private ReadType readType = ReadType.DEFAULT;
189
190  private boolean needCursorResult = false;
191
192  /**
193   * Create a Scan operation across all rows.
194   */
195  public Scan() {
196  }
197
198  /**
199   * @deprecated since 2.0.0 and will be removed in 3.0.0. Use
200   *             {@code new Scan().withStartRow(startRow).setFilter(filter)} instead.
201   * @see <a href="https://issues.apache.org/jira/browse/HBASE-17320">HBASE-17320</a>
202   */
203  @Deprecated
204  public Scan(byte[] startRow, Filter filter) {
205    this(startRow);
206    this.filter = filter;
207  }
208
209  /**
210   * Create a Scan operation starting at the specified row.
211   * <p>
212   * If the specified row does not exist, the Scanner will start from the next closest row after the
213   * specified row.
214   * @param startRow row to start scanner at or after
215   * @deprecated since 2.0.0 and will be removed in 3.0.0. Use
216   *             {@code new Scan().withStartRow(startRow)} instead.
217   * @see <a href="https://issues.apache.org/jira/browse/HBASE-17320">HBASE-17320</a>
218   */
219  @Deprecated
220  public Scan(byte[] startRow) {
221    setStartRow(startRow);
222  }
223
224  /**
225   * Create a Scan operation for the range of rows specified.
226   * @param startRow row to start scanner at or after (inclusive)
227   * @param stopRow  row to stop scanner before (exclusive)
228   * @deprecated since 2.0.0 and will be removed in 3.0.0. Use
229   *             {@code new Scan().withStartRow(startRow).withStopRow(stopRow)} instead.
230   * @see <a href="https://issues.apache.org/jira/browse/HBASE-17320">HBASE-17320</a>
231   */
232  @Deprecated
233  public Scan(byte[] startRow, byte[] stopRow) {
234    setStartRow(startRow);
235    setStopRow(stopRow);
236  }
237
238  /**
239   * Creates a new instance of this class while copying all values.
240   * @param scan The scan instance to copy from.
241   * @throws IOException When copying the values fails.
242   */
243  public Scan(Scan scan) throws IOException {
244    startRow = scan.getStartRow();
245    includeStartRow = scan.includeStartRow();
246    stopRow = scan.getStopRow();
247    includeStopRow = scan.includeStopRow();
248    maxVersions = scan.getMaxVersions();
249    batch = scan.getBatch();
250    storeLimit = scan.getMaxResultsPerColumnFamily();
251    storeOffset = scan.getRowOffsetPerColumnFamily();
252    caching = scan.getCaching();
253    maxResultSize = scan.getMaxResultSize();
254    cacheBlocks = scan.getCacheBlocks();
255    filter = scan.getFilter(); // clone?
256    loadColumnFamiliesOnDemand = scan.getLoadColumnFamiliesOnDemandValue();
257    consistency = scan.getConsistency();
258    this.setIsolationLevel(scan.getIsolationLevel());
259    reversed = scan.isReversed();
260    asyncPrefetch = scan.isAsyncPrefetch();
261    small = scan.isSmall();
262    allowPartialResults = scan.getAllowPartialResults();
263    tr = scan.getTimeRange(); // TimeRange is immutable
264    Map<byte[], NavigableSet<byte[]>> fams = scan.getFamilyMap();
265    for (Map.Entry<byte[], NavigableSet<byte[]>> entry : fams.entrySet()) {
266      byte[] fam = entry.getKey();
267      NavigableSet<byte[]> cols = entry.getValue();
268      if (cols != null && cols.size() > 0) {
269        for (byte[] col : cols) {
270          addColumn(fam, col);
271        }
272      } else {
273        addFamily(fam);
274      }
275    }
276    for (Map.Entry<String, byte[]> attr : scan.getAttributesMap().entrySet()) {
277      setAttribute(attr.getKey(), attr.getValue());
278    }
279    for (Map.Entry<byte[], TimeRange> entry : scan.getColumnFamilyTimeRange().entrySet()) {
280      TimeRange tr = entry.getValue();
281      setColumnFamilyTimeRange(entry.getKey(), tr.getMin(), tr.getMax());
282    }
283    this.mvccReadPoint = scan.getMvccReadPoint();
284    this.limit = scan.getLimit();
285    this.needCursorResult = scan.isNeedCursorResult();
286    setPriority(scan.getPriority());
287    readType = scan.getReadType();
288    super.setReplicaId(scan.getReplicaId());
289    super.setQueryMetricsEnabled(scan.isQueryMetricsEnabled());
290  }
291
292  /**
293   * Builds a scan object with the same specs as get.
294   * @param get get to model scan after
295   */
296  public Scan(Get get) {
297    this.startRow = get.getRow();
298    this.includeStartRow = true;
299    this.stopRow = get.getRow();
300    this.includeStopRow = true;
301    this.filter = get.getFilter();
302    this.cacheBlocks = get.getCacheBlocks();
303    this.maxVersions = get.getMaxVersions();
304    this.storeLimit = get.getMaxResultsPerColumnFamily();
305    this.storeOffset = get.getRowOffsetPerColumnFamily();
306    this.tr = get.getTimeRange();
307    this.familyMap = get.getFamilyMap();
308    this.asyncPrefetch = false;
309    this.consistency = get.getConsistency();
310    this.setIsolationLevel(get.getIsolationLevel());
311    this.loadColumnFamiliesOnDemand = get.getLoadColumnFamiliesOnDemandValue();
312    for (Map.Entry<String, byte[]> attr : get.getAttributesMap().entrySet()) {
313      setAttribute(attr.getKey(), attr.getValue());
314    }
315    for (Map.Entry<byte[], TimeRange> entry : get.getColumnFamilyTimeRange().entrySet()) {
316      TimeRange tr = entry.getValue();
317      setColumnFamilyTimeRange(entry.getKey(), tr.getMin(), tr.getMax());
318    }
319    this.mvccReadPoint = -1L;
320    setPriority(get.getPriority());
321    super.setReplicaId(get.getReplicaId());
322    super.setQueryMetricsEnabled(get.isQueryMetricsEnabled());
323  }
324
325  public boolean isGetScan() {
326    return includeStartRow && includeStopRow
327      && ClientUtil.areScanStartRowAndStopRowEqual(this.startRow, this.stopRow);
328  }
329
330  /**
331   * Get all columns from the specified family.
332   * <p>
333   * Overrides previous calls to addColumn for this family.
334   * @param family family name
335   */
336  public Scan addFamily(byte[] family) {
337    familyMap.remove(family);
338    familyMap.put(family, null);
339    return this;
340  }
341
342  /**
343   * Get the column from the specified family with the specified qualifier.
344   * <p>
345   * Overrides previous calls to addFamily for this family.
346   * @param family    family name
347   * @param qualifier column qualifier
348   */
349  public Scan addColumn(byte[] family, byte[] qualifier) {
350    NavigableSet<byte[]> set = familyMap.get(family);
351    if (set == null) {
352      set = new TreeSet<>(Bytes.BYTES_COMPARATOR);
353      familyMap.put(family, set);
354    }
355    if (qualifier == null) {
356      qualifier = HConstants.EMPTY_BYTE_ARRAY;
357    }
358    set.add(qualifier);
359    return this;
360  }
361
362  /**
363   * Get versions of columns only within the specified timestamp range, [minStamp, maxStamp). Note,
364   * default maximum versions to return is 1. If your time range spans more than one version and you
365   * want all versions returned, up the number of versions beyond the default.
366   * @param minStamp minimum timestamp value, inclusive
367   * @param maxStamp maximum timestamp value, exclusive
368   * @see #setMaxVersions()
369   * @see #setMaxVersions(int)
370   */
371  public Scan setTimeRange(long minStamp, long maxStamp) throws IOException {
372    tr = new TimeRange(minStamp, maxStamp);
373    return this;
374  }
375
376  /**
377   * Get versions of columns with the specified timestamp. Note, default maximum versions to return
378   * is 1. If your time range spans more than one version and you want all versions returned, up the
379   * number of versions beyond the defaut.
380   * @param timestamp version timestamp
381   * @see #setMaxVersions()
382   * @see #setMaxVersions(int)
383   * @deprecated As of release 2.0.0, this will be removed in HBase 3.0.0. Use
384   *             {@link #setTimestamp(long)} instead
385   */
386  @Deprecated
387  public Scan setTimeStamp(long timestamp) throws IOException {
388    return this.setTimestamp(timestamp);
389  }
390
391  /**
392   * Get versions of columns with the specified timestamp. Note, default maximum versions to return
393   * is 1. If your time range spans more than one version and you want all versions returned, up the
394   * number of versions beyond the defaut.
395   * @param timestamp version timestamp
396   * @see #setMaxVersions()
397   * @see #setMaxVersions(int)
398   */
399  public Scan setTimestamp(long timestamp) {
400    try {
401      tr = new TimeRange(timestamp, timestamp + 1);
402    } catch (Exception e) {
403      // This should never happen, unless integer overflow or something extremely wrong...
404      LOG.error("TimeRange failed, likely caused by integer overflow. ", e);
405      throw e;
406    }
407
408    return this;
409  }
410
411  @Override
412  public Scan setColumnFamilyTimeRange(byte[] cf, long minStamp, long maxStamp) {
413    super.setColumnFamilyTimeRange(cf, minStamp, maxStamp);
414    return this;
415  }
416
417  /**
418   * Set the start row of the scan.
419   * <p>
420   * If the specified row does not exist, the Scanner will start from the next closest row after the
421   * specified row.
422   * <p>
423   * <b>Note:</b> <strong>Do NOT use this in combination with {@link #setRowPrefixFilter(byte[])} or
424   * {@link #setStartStopRowForPrefixScan(byte[])}.</strong> Doing so will make the scan result
425   * unexpected or even undefined.
426   * </p>
427   * @param startRow row to start scanner at or after
428   * @throws IllegalArgumentException if startRow does not meet criteria for a row key (when length
429   *                                  exceeds {@link HConstants#MAX_ROW_LENGTH})
430   * @deprecated since 2.0.0 and will be removed in 3.0.0. Use {@link #withStartRow(byte[])}
431   *             instead. This method may change the inclusive of the stop row to keep compatible
432   *             with the old behavior.
433   * @see #withStartRow(byte[])
434   * @see <a href="https://issues.apache.org/jira/browse/HBASE-17320">HBASE-17320</a>
435   */
436  @Deprecated
437  public Scan setStartRow(byte[] startRow) {
438    withStartRow(startRow);
439    if (ClientUtil.areScanStartRowAndStopRowEqual(this.startRow, this.stopRow)) {
440      // for keeping the old behavior that a scan with the same start and stop row is a get scan.
441      this.includeStopRow = true;
442    }
443    return this;
444  }
445
446  /**
447   * Set the start row of the scan.
448   * <p>
449   * If the specified row does not exist, the Scanner will start from the next closest row after the
450   * specified row.
451   * @param startRow row to start scanner at or after
452   * @throws IllegalArgumentException if startRow does not meet criteria for a row key (when length
453   *                                  exceeds {@link HConstants#MAX_ROW_LENGTH})
454   */
455  public Scan withStartRow(byte[] startRow) {
456    return withStartRow(startRow, true);
457  }
458
459  /**
460   * Set the start row of the scan.
461   * <p>
462   * If the specified row does not exist, or the {@code inclusive} is {@code false}, the Scanner
463   * will start from the next closest row after the specified row.
464   * <p>
465   * <b>Note:</b> <strong>Do NOT use this in combination with {@link #setRowPrefixFilter(byte[])} or
466   * {@link #setStartStopRowForPrefixScan(byte[])}.</strong> Doing so will make the scan result
467   * unexpected or even undefined.
468   * </p>
469   * @param startRow  row to start scanner at or after
470   * @param inclusive whether we should include the start row when scan
471   * @throws IllegalArgumentException if startRow does not meet criteria for a row key (when length
472   *                                  exceeds {@link HConstants#MAX_ROW_LENGTH})
473   */
474  public Scan withStartRow(byte[] startRow, boolean inclusive) {
475    if (Bytes.len(startRow) > HConstants.MAX_ROW_LENGTH) {
476      throw new IllegalArgumentException("startRow's length must be less than or equal to "
477        + HConstants.MAX_ROW_LENGTH + " to meet the criteria" + " for a row key.");
478    }
479    this.startRow = startRow;
480    this.includeStartRow = inclusive;
481    return this;
482  }
483
484  /**
485   * Set the stop row of the scan.
486   * <p>
487   * The scan will include rows that are lexicographically less than the provided stopRow.
488   * <p>
489   * <b>Note:</b> <strong>Do NOT use this in combination with {@link #setRowPrefixFilter(byte[])} or
490   * {@link #setStartStopRowForPrefixScan(byte[])}.</strong> Doing so will make the scan result
491   * unexpected or even undefined.
492   * </p>
493   * @param stopRow row to end at (exclusive)
494   * @throws IllegalArgumentException if stopRow does not meet criteria for a row key (when length
495   *                                  exceeds {@link HConstants#MAX_ROW_LENGTH})
496   * @deprecated since 2.0.0 and will be removed in 3.0.0. Use {@link #withStopRow(byte[])} instead.
497   *             This method may change the inclusive of the stop row to keep compatible with the
498   *             old behavior.
499   * @see #withStopRow(byte[])
500   * @see <a href="https://issues.apache.org/jira/browse/HBASE-17320">HBASE-17320</a>
501   */
502  @Deprecated
503  public Scan setStopRow(byte[] stopRow) {
504    withStopRow(stopRow);
505    if (ClientUtil.areScanStartRowAndStopRowEqual(this.startRow, this.stopRow)) {
506      // for keeping the old behavior that a scan with the same start and stop row is a get scan.
507      this.includeStopRow = true;
508    }
509    return this;
510  }
511
512  /**
513   * Set the stop row of the scan.
514   * <p>
515   * The scan will include rows that are lexicographically less than the provided stopRow.
516   * <p>
517   * <b>Note:</b> When doing a filter for a rowKey <u>Prefix</u> use
518   * {@link #setRowPrefixFilter(byte[])}. The 'trailing 0' will not yield the desired result.
519   * </p>
520   * @param stopRow row to end at (exclusive)
521   * @throws IllegalArgumentException if stopRow does not meet criteria for a row key (when length
522   *                                  exceeds {@link HConstants#MAX_ROW_LENGTH})
523   */
524  public Scan withStopRow(byte[] stopRow) {
525    return withStopRow(stopRow, false);
526  }
527
528  /**
529   * Set the stop row of the scan.
530   * <p>
531   * The scan will include rows that are lexicographically less than (or equal to if
532   * {@code inclusive} is {@code true}) the provided stopRow.
533   * <p>
534   * <b>Note:</b> <strong>Do NOT use this in combination with {@link #setRowPrefixFilter(byte[])} or
535   * {@link #setStartStopRowForPrefixScan(byte[])}.</strong> Doing so will make the scan result
536   * unexpected or even undefined.
537   * </p>
538   * @param stopRow   row to end at
539   * @param inclusive whether we should include the stop row when scan
540   * @throws IllegalArgumentException if stopRow does not meet criteria for a row key (when length
541   *                                  exceeds {@link HConstants#MAX_ROW_LENGTH})
542   */
543  public Scan withStopRow(byte[] stopRow, boolean inclusive) {
544    if (Bytes.len(stopRow) > HConstants.MAX_ROW_LENGTH) {
545      throw new IllegalArgumentException("stopRow's length must be less than or equal to "
546        + HConstants.MAX_ROW_LENGTH + " to meet the criteria" + " for a row key.");
547    }
548    this.stopRow = stopRow;
549    this.includeStopRow = inclusive;
550    return this;
551  }
552
553  /**
554   * <p>
555   * Set a filter (using stopRow and startRow) so the result set only contains rows where the rowKey
556   * starts with the specified prefix.
557   * </p>
558   * <p>
559   * This is a utility method that converts the desired rowPrefix into the appropriate values for
560   * the startRow and stopRow to achieve the desired result.
561   * </p>
562   * <p>
563   * This can safely be used in combination with setFilter.
564   * </p>
565   * <p>
566   * <strong>This CANNOT be used in combination with withStartRow and/or withStopRow.</strong> Such
567   * a combination will yield unexpected and even undefined results.
568   * </p>
569   * @param rowPrefix the prefix all rows must start with. (Set <i>null</i> to remove the filter.)
570   * @deprecated since 2.5.0, will be removed in 4.0.0. The name of this method is considered to be
571   *             confusing as it does not use a {@link Filter} but uses setting the startRow and
572   *             stopRow instead. Use {@link #setStartStopRowForPrefixScan(byte[])} instead.
573   */
574  public Scan setRowPrefixFilter(byte[] rowPrefix) {
575    return setStartStopRowForPrefixScan(rowPrefix);
576  }
577
578  /**
579   * <p>
580   * Set a filter (using stopRow and startRow) so the result set only contains rows where the rowKey
581   * starts with the specified prefix.
582   * </p>
583   * <p>
584   * This is a utility method that converts the desired rowPrefix into the appropriate values for
585   * the startRow and stopRow to achieve the desired result.
586   * </p>
587   * <p>
588   * This can safely be used in combination with setFilter.
589   * </p>
590   * <p>
591   * <strong>This CANNOT be used in combination with withStartRow and/or withStopRow.</strong> Such
592   * a combination will yield unexpected and even undefined results.
593   * </p>
594   * @param rowPrefix the prefix all rows must start with. (Set <i>null</i> to remove the filter.)
595   */
596  public Scan setStartStopRowForPrefixScan(byte[] rowPrefix) {
597    if (rowPrefix == null) {
598      setStartRow(HConstants.EMPTY_START_ROW);
599      setStopRow(HConstants.EMPTY_END_ROW);
600    } else {
601      this.setStartRow(rowPrefix);
602      this.setStopRow(ClientUtil.calculateTheClosestNextRowKeyForPrefix(rowPrefix));
603    }
604    return this;
605  }
606
607  /**
608   * Get all available versions.
609   * @deprecated since 2.0.0 and will be removed in 3.0.0. It is easy to misunderstand with column
610   *             family's max versions, so use {@link #readAllVersions()} instead.
611   * @see #readAllVersions()
612   * @see <a href="https://issues.apache.org/jira/browse/HBASE-17125">HBASE-17125</a>
613   */
614  @Deprecated
615  public Scan setMaxVersions() {
616    return readAllVersions();
617  }
618
619  /**
620   * Get up to the specified number of versions of each column.
621   * @param maxVersions maximum versions for each column
622   * @deprecated since 2.0.0 and will be removed in 3.0.0. It is easy to misunderstand with column
623   *             family's max versions, so use {@link #readVersions(int)} instead.
624   * @see #readVersions(int)
625   * @see <a href="https://issues.apache.org/jira/browse/HBASE-17125">HBASE-17125</a>
626   */
627  @Deprecated
628  public Scan setMaxVersions(int maxVersions) {
629    return readVersions(maxVersions);
630  }
631
632  /**
633   * Get all available versions.
634   */
635  public Scan readAllVersions() {
636    this.maxVersions = Integer.MAX_VALUE;
637    return this;
638  }
639
640  /**
641   * Get up to the specified number of versions of each column.
642   * @param versions specified number of versions for each column
643   */
644  public Scan readVersions(int versions) {
645    this.maxVersions = versions;
646    return this;
647  }
648
649  /**
650   * Set the maximum number of cells to return for each call to next(). Callers should be aware that
651   * this is not equivalent to calling {@link #setAllowPartialResults(boolean)}. If you don't allow
652   * partial results, the number of cells in each Result must equal to your batch setting unless it
653   * is the last Result for current row. So this method is helpful in paging queries. If you just
654   * want to prevent OOM at client, use setAllowPartialResults(true) is better.
655   * @param batch the maximum number of values
656   * @see Result#mayHaveMoreCellsInRow()
657   */
658  public Scan setBatch(int batch) {
659    if (this.hasFilter() && this.filter.hasFilterRow()) {
660      throw new IncompatibleFilterException(
661        "Cannot set batch on a scan using a filter" + " that returns true for filter.hasFilterRow");
662    }
663    this.batch = batch;
664    return this;
665  }
666
667  /**
668   * Set the maximum number of values to return per row per Column Family
669   * @param limit the maximum number of values returned / row / CF
670   */
671  public Scan setMaxResultsPerColumnFamily(int limit) {
672    this.storeLimit = limit;
673    return this;
674  }
675
676  /**
677   * Set offset for the row per Column Family.
678   * @param offset is the number of kvs that will be skipped.
679   */
680  public Scan setRowOffsetPerColumnFamily(int offset) {
681    this.storeOffset = offset;
682    return this;
683  }
684
685  /**
686   * Set the number of rows for caching that will be passed to scanners. If not set, the
687   * Configuration setting {@link HConstants#HBASE_CLIENT_SCANNER_CACHING} will apply. Higher
688   * caching values will enable faster scanners but will use more memory.
689   * @param caching the number of rows for caching
690   */
691  public Scan setCaching(int caching) {
692    this.caching = caching;
693    return this;
694  }
695
696  /** Returns the maximum result size in bytes. See {@link #setMaxResultSize(long)} */
697  public long getMaxResultSize() {
698    return maxResultSize;
699  }
700
701  /**
702   * Set the maximum result size. The default is -1; this means that no specific maximum result size
703   * will be set for this scan, and the global configured value will be used instead. (Defaults to
704   * unlimited).
705   * @param maxResultSize The maximum result size in bytes.
706   */
707  public Scan setMaxResultSize(long maxResultSize) {
708    this.maxResultSize = maxResultSize;
709    return this;
710  }
711
712  @Override
713  public Scan setFilter(Filter filter) {
714    super.setFilter(filter);
715    return this;
716  }
717
718  /**
719   * Setting the familyMap
720   * @param familyMap map of family to qualifier
721   */
722  public Scan setFamilyMap(Map<byte[], NavigableSet<byte[]>> familyMap) {
723    this.familyMap = familyMap;
724    return this;
725  }
726
727  /**
728   * Getting the familyMap
729   */
730  public Map<byte[], NavigableSet<byte[]>> getFamilyMap() {
731    return this.familyMap;
732  }
733
734  /** Returns the number of families in familyMap */
735  public int numFamilies() {
736    if (hasFamilies()) {
737      return this.familyMap.size();
738    }
739    return 0;
740  }
741
742  /** Returns true if familyMap is non empty, false otherwise */
743  public boolean hasFamilies() {
744    return !this.familyMap.isEmpty();
745  }
746
747  /** Returns the keys of the familyMap */
748  public byte[][] getFamilies() {
749    if (hasFamilies()) {
750      return this.familyMap.keySet().toArray(new byte[0][0]);
751    }
752    return null;
753  }
754
755  /** Returns the startrow */
756  public byte[] getStartRow() {
757    return this.startRow;
758  }
759
760  /** Returns if we should include start row when scan */
761  public boolean includeStartRow() {
762    return includeStartRow;
763  }
764
765  /** Returns the stoprow */
766  public byte[] getStopRow() {
767    return this.stopRow;
768  }
769
770  /** Returns if we should include stop row when scan */
771  public boolean includeStopRow() {
772    return includeStopRow;
773  }
774
775  /** Returns the max number of versions to fetch */
776  public int getMaxVersions() {
777    return this.maxVersions;
778  }
779
780  /** Returns maximum number of values to return for a single call to next() */
781  public int getBatch() {
782    return this.batch;
783  }
784
785  /** Returns maximum number of values to return per row per CF */
786  public int getMaxResultsPerColumnFamily() {
787    return this.storeLimit;
788  }
789
790  /**
791   * Method for retrieving the scan's offset per row per column family (#kvs to be skipped)
792   * @return row offset
793   */
794  public int getRowOffsetPerColumnFamily() {
795    return this.storeOffset;
796  }
797
798  /** Returns caching the number of rows fetched when calling next on a scanner */
799  public int getCaching() {
800    return this.caching;
801  }
802
803  /** Returns TimeRange */
804  public TimeRange getTimeRange() {
805    return this.tr;
806  }
807
808  /** Returns RowFilter */
809  @Override
810  public Filter getFilter() {
811    return filter;
812  }
813
814  /** Returns true is a filter has been specified, false if not */
815  public boolean hasFilter() {
816    return filter != null;
817  }
818
819  /**
820   * Set whether blocks should be cached for this Scan.
821   * <p>
822   * This is true by default. When true, default settings of the table and family are used (this
823   * will never override caching blocks if the block cache is disabled for that family or entirely).
824   * @param cacheBlocks if false, default settings are overridden and blocks will not be cached
825   */
826  public Scan setCacheBlocks(boolean cacheBlocks) {
827    this.cacheBlocks = cacheBlocks;
828    return this;
829  }
830
831  /**
832   * Get whether blocks should be cached for this Scan.
833   * @return true if default caching should be used, false if blocks should not be cached
834   */
835  public boolean getCacheBlocks() {
836    return cacheBlocks;
837  }
838
839  /**
840   * Set whether this scan is a reversed one
841   * <p>
842   * This is false by default which means forward(normal) scan.
843   * @param reversed if true, scan will be backward order
844   */
845  public Scan setReversed(boolean reversed) {
846    this.reversed = reversed;
847    return this;
848  }
849
850  /**
851   * Get whether this scan is a reversed one.
852   * @return true if backward scan, false if forward(default) scan
853   */
854  public boolean isReversed() {
855    return reversed;
856  }
857
858  /**
859   * Setting whether the caller wants to see the partial results when server returns
860   * less-than-expected cells. It is helpful while scanning a huge row to prevent OOM at client. By
861   * default this value is false and the complete results will be assembled client side before being
862   * delivered to the caller.
863   * @see Result#mayHaveMoreCellsInRow()
864   * @see #setBatch(int)
865   */
866  public Scan setAllowPartialResults(final boolean allowPartialResults) {
867    this.allowPartialResults = allowPartialResults;
868    return this;
869  }
870
871  /**
872   * Returns true when the constructor of this scan understands that the results they will see may
873   * only represent a partial portion of a row. The entire row would be retrieved by subsequent
874   * calls to {@link ResultScanner#next()}
875   */
876  public boolean getAllowPartialResults() {
877    return allowPartialResults;
878  }
879
880  @Override
881  public Scan setLoadColumnFamiliesOnDemand(boolean value) {
882    super.setLoadColumnFamiliesOnDemand(value);
883    return this;
884  }
885
886  /**
887   * Compile the table and column family (i.e. schema) information into a String. Useful for parsing
888   * and aggregation by debugging, logging, and administration tools.
889   */
890  @Override
891  public Map<String, Object> getFingerprint() {
892    Map<String, Object> map = new HashMap<>();
893    List<String> families = new ArrayList<>();
894    if (this.familyMap.isEmpty()) {
895      map.put("families", "ALL");
896      return map;
897    } else {
898      map.put("families", families);
899    }
900    for (Map.Entry<byte[], NavigableSet<byte[]>> entry : this.familyMap.entrySet()) {
901      families.add(Bytes.toStringBinary(entry.getKey()));
902    }
903    return map;
904  }
905
906  /**
907   * Compile the details beyond the scope of getFingerprint (row, columns, timestamps, etc.) into a
908   * Map along with the fingerprinted information. Useful for debugging, logging, and administration
909   * tools.
910   * @param maxCols a limit on the number of columns output prior to truncation
911   */
912  @Override
913  public Map<String, Object> toMap(int maxCols) {
914    // start with the fingerprint map and build on top of it
915    Map<String, Object> map = getFingerprint();
916    // map from families to column list replaces fingerprint's list of families
917    Map<String, List<String>> familyColumns = new HashMap<>();
918    map.put("families", familyColumns);
919    // add scalar information first
920    map.put("startRow", Bytes.toStringBinary(this.startRow));
921    map.put("stopRow", Bytes.toStringBinary(this.stopRow));
922    map.put("maxVersions", this.maxVersions);
923    map.put("batch", this.batch);
924    map.put("caching", this.caching);
925    map.put("maxResultSize", this.maxResultSize);
926    map.put("cacheBlocks", this.cacheBlocks);
927    map.put("loadColumnFamiliesOnDemand", this.loadColumnFamiliesOnDemand);
928    List<Long> timeRange = new ArrayList<>(2);
929    timeRange.add(this.tr.getMin());
930    timeRange.add(this.tr.getMax());
931    map.put("timeRange", timeRange);
932    int colCount = 0;
933    // iterate through affected families and list out up to maxCols columns
934    for (Map.Entry<byte[], NavigableSet<byte[]>> entry : this.familyMap.entrySet()) {
935      List<String> columns = new ArrayList<>();
936      familyColumns.put(Bytes.toStringBinary(entry.getKey()), columns);
937      if (entry.getValue() == null) {
938        colCount++;
939        --maxCols;
940        columns.add("ALL");
941      } else {
942        colCount += entry.getValue().size();
943        if (maxCols <= 0) {
944          continue;
945        }
946        for (byte[] column : entry.getValue()) {
947          if (--maxCols <= 0) {
948            continue;
949          }
950          columns.add(Bytes.toStringBinary(column));
951        }
952      }
953    }
954    map.put("totalColumns", colCount);
955    if (this.filter != null) {
956      map.put("filter", this.filter.toString());
957    }
958    // add the id if set
959    if (getId() != null) {
960      map.put("id", getId());
961    }
962    map.put("includeStartRow", includeStartRow);
963    map.put("includeStopRow", includeStopRow);
964    map.put("allowPartialResults", allowPartialResults);
965    map.put("storeLimit", storeLimit);
966    map.put("storeOffset", storeOffset);
967    map.put("reversed", reversed);
968    if (null != asyncPrefetch) {
969      map.put("asyncPrefetch", asyncPrefetch);
970    }
971    map.put("mvccReadPoint", mvccReadPoint);
972    map.put("limit", limit);
973    map.put("readType", readType);
974    map.put("needCursorResult", needCursorResult);
975    map.put("targetReplicaId", targetReplicaId);
976    map.put("consistency", consistency);
977    if (!colFamTimeRangeMap.isEmpty()) {
978      Map<String, List<Long>> colFamTimeRangeMapStr = colFamTimeRangeMap.entrySet().stream()
979        .collect(Collectors.toMap((e) -> Bytes.toStringBinary(e.getKey()), e -> {
980          TimeRange value = e.getValue();
981          List<Long> rangeList = new ArrayList<>();
982          rangeList.add(value.getMin());
983          rangeList.add(value.getMax());
984          return rangeList;
985        }));
986
987      map.put("colFamTimeRangeMap", colFamTimeRangeMapStr);
988    }
989    map.put("priority", getPriority());
990    map.put("queryMetricsEnabled", queryMetricsEnabled);
991    return map;
992  }
993
994  /**
995   * Enable/disable "raw" mode for this scan. If "raw" is enabled the scan will return all delete
996   * marker and deleted rows that have not been collected, yet. This is mostly useful for Scan on
997   * column families that have KEEP_DELETED_ROWS enabled. It is an error to specify any column when
998   * "raw" is set.
999   * @param raw True/False to enable/disable "raw" mode.
1000   */
1001  public Scan setRaw(boolean raw) {
1002    setAttribute(RAW_ATTR, Bytes.toBytes(raw));
1003    return this;
1004  }
1005
1006  /** Returns True if this Scan is in "raw" mode. */
1007  public boolean isRaw() {
1008    byte[] attr = getAttribute(RAW_ATTR);
1009    return attr == null ? false : Bytes.toBoolean(attr);
1010  }
1011
1012  /**
1013   * Set whether this scan is a small scan
1014   * <p>
1015   * Small scan should use pread and big scan can use seek + read seek + read is fast but can cause
1016   * two problem (1) resource contention (2) cause too much network io [89-fb] Using pread for
1017   * non-compaction read request https://issues.apache.org/jira/browse/HBASE-7266 On the other hand,
1018   * if setting it true, we would do openScanner,next,closeScanner in one RPC call. It means the
1019   * better performance for small scan. [HBASE-9488]. Generally, if the scan range is within one
1020   * data block(64KB), it could be considered as a small scan.
1021   * @param small set if that should use read type of PREAD
1022   * @deprecated since 2.0.0 and will be removed in 3.0.0. Use {@link #setLimit(int)} and
1023   *             {@link #setReadType(ReadType)} instead. And for the one rpc optimization, now we
1024   *             will also fetch data when openScanner, and if the number of rows reaches the limit
1025   *             then we will close the scanner automatically which means we will fall back to one
1026   *             rpc.
1027   * @see #setLimit(int)
1028   * @see #setReadType(ReadType)
1029   * @see <a href="https://issues.apache.org/jira/browse/HBASE-17045">HBASE-17045</a>
1030   */
1031  @Deprecated
1032  public Scan setSmall(boolean small) {
1033    this.small = small;
1034    if (small) {
1035      this.readType = ReadType.PREAD;
1036    }
1037    return this;
1038  }
1039
1040  /**
1041   * Get whether this scan is a small scan
1042   * @return true if small scan
1043   * @deprecated since 2.0.0 and will be removed in 3.0.0. See the comment of
1044   *             {@link #setSmall(boolean)}
1045   * @see <a href="https://issues.apache.org/jira/browse/HBASE-17045">HBASE-17045</a>
1046   */
1047  @Deprecated
1048  public boolean isSmall() {
1049    return small;
1050  }
1051
1052  @Override
1053  public Scan setAttribute(String name, byte[] value) {
1054    super.setAttribute(name, value);
1055    return this;
1056  }
1057
1058  @Override
1059  public Scan setId(String id) {
1060    super.setId(id);
1061    return this;
1062  }
1063
1064  @Override
1065  public Scan setAuthorizations(Authorizations authorizations) {
1066    super.setAuthorizations(authorizations);
1067    return this;
1068  }
1069
1070  @Override
1071  public Scan setACL(Map<String, Permission> perms) {
1072    super.setACL(perms);
1073    return this;
1074  }
1075
1076  @Override
1077  public Scan setACL(String user, Permission perms) {
1078    super.setACL(user, perms);
1079    return this;
1080  }
1081
1082  @Override
1083  public Scan setConsistency(Consistency consistency) {
1084    super.setConsistency(consistency);
1085    return this;
1086  }
1087
1088  @Override
1089  public Scan setReplicaId(int Id) {
1090    super.setReplicaId(Id);
1091    return this;
1092  }
1093
1094  @Override
1095  public Scan setIsolationLevel(IsolationLevel level) {
1096    super.setIsolationLevel(level);
1097    return this;
1098  }
1099
1100  @Override
1101  public Scan setPriority(int priority) {
1102    super.setPriority(priority);
1103    return this;
1104  }
1105
1106  /**
1107   * Enable collection of {@link ScanMetrics}. For advanced users. While disabling scan metrics,
1108   * will also disable region level scan metrics.
1109   * @param enabled Set to true to enable accumulating scan metrics
1110   */
1111  public Scan setScanMetricsEnabled(final boolean enabled) {
1112    setAttribute(Scan.SCAN_ATTRIBUTES_METRICS_ENABLE, Bytes.toBytes(Boolean.valueOf(enabled)));
1113    if (!enabled) {
1114      setEnableScanMetricsByRegion(false);
1115    }
1116    return this;
1117  }
1118
1119  /** Returns True if collection of scan metrics is enabled. For advanced users. */
1120  public boolean isScanMetricsEnabled() {
1121    byte[] attr = getAttribute(Scan.SCAN_ATTRIBUTES_METRICS_ENABLE);
1122    return attr == null ? false : Bytes.toBoolean(attr);
1123  }
1124
1125  /**
1126   * @return Metrics on this Scan, if metrics were enabled.
1127   * @see #setScanMetricsEnabled(boolean)
1128   * @deprecated Use {@link ResultScanner#getScanMetrics()} instead. And notice that, please do not
1129   *             use this method and {@link ResultScanner#getScanMetrics()} together, the metrics
1130   *             will be messed up.
1131   */
1132  @Deprecated
1133  public ScanMetrics getScanMetrics() {
1134    byte[] bytes = getAttribute(Scan.SCAN_ATTRIBUTES_METRICS_DATA);
1135    if (bytes == null) return null;
1136    return ProtobufUtil.toScanMetrics(bytes);
1137  }
1138
1139  public Boolean isAsyncPrefetch() {
1140    return asyncPrefetch;
1141  }
1142
1143  public Scan setAsyncPrefetch(boolean asyncPrefetch) {
1144    this.asyncPrefetch = asyncPrefetch;
1145    return this;
1146  }
1147
1148  /** Returns the limit of rows for this scan */
1149  public int getLimit() {
1150    return limit;
1151  }
1152
1153  /**
1154   * Set the limit of rows for this scan. We will terminate the scan if the number of returned rows
1155   * reaches this value.
1156   * <p>
1157   * This condition will be tested at last, after all other conditions such as stopRow, filter, etc.
1158   * @param limit the limit of rows for this scan
1159   */
1160  public Scan setLimit(int limit) {
1161    this.limit = limit;
1162    return this;
1163  }
1164
1165  /**
1166   * Call this when you only want to get one row. It will set {@code limit} to {@code 1}, and also
1167   * set {@code readType} to {@link ReadType#PREAD}.
1168   */
1169  public Scan setOneRowLimit() {
1170    return setLimit(1).setReadType(ReadType.PREAD);
1171  }
1172
1173  @InterfaceAudience.Public
1174  public enum ReadType {
1175    DEFAULT,
1176    STREAM,
1177    PREAD
1178  }
1179
1180  /** Returns the read type for this scan */
1181  public ReadType getReadType() {
1182    return readType;
1183  }
1184
1185  /**
1186   * Set the read type for this scan.
1187   * <p>
1188   * Notice that we may choose to use pread even if you specific {@link ReadType#STREAM} here. For
1189   * example, we will always use pread if this is a get scan.
1190   */
1191  public Scan setReadType(ReadType readType) {
1192    this.readType = readType;
1193    return this;
1194  }
1195
1196  /**
1197   * Get the mvcc read point used to open a scanner.
1198   */
1199  long getMvccReadPoint() {
1200    return mvccReadPoint;
1201  }
1202
1203  /**
1204   * Set the mvcc read point used to open a scanner.
1205   */
1206  Scan setMvccReadPoint(long mvccReadPoint) {
1207    this.mvccReadPoint = mvccReadPoint;
1208    return this;
1209  }
1210
1211  /**
1212   * Set the mvcc read point to -1 which means do not use it.
1213   */
1214  Scan resetMvccReadPoint() {
1215    return setMvccReadPoint(-1L);
1216  }
1217
1218  /**
1219   * When the server is slow or we scan a table with many deleted data or we use a sparse filter,
1220   * the server will response heartbeat to prevent timeout. However the scanner will return a Result
1221   * only when client can do it. So if there are many heartbeats, the blocking time on
1222   * ResultScanner#next() may be very long, which is not friendly to online services. Set this to
1223   * true then you can get a special Result whose #isCursor() returns true and is not contains any
1224   * real data. It only tells you where the server has scanned. You can call next to continue
1225   * scanning or open a new scanner with this row key as start row whenever you want. Users can get
1226   * a cursor when and only when there is a response from the server but we can not return a Result
1227   * to users, for example, this response is a heartbeat or there are partial cells but users do not
1228   * allow partial result. Now the cursor is in row level which means the special Result will only
1229   * contains a row key. {@link Result#isCursor()} {@link Result#getCursor()} {@link Cursor}
1230   */
1231  public Scan setNeedCursorResult(boolean needCursorResult) {
1232    this.needCursorResult = needCursorResult;
1233    return this;
1234  }
1235
1236  public boolean isNeedCursorResult() {
1237    return needCursorResult;
1238  }
1239
1240  /**
1241   * Create a new Scan with a cursor. It only set the position information like start row key. The
1242   * others (like cfs, stop row, limit) should still be filled in by the user.
1243   * {@link Result#isCursor()} {@link Result#getCursor()} {@link Cursor}
1244   */
1245  public static Scan createScanFromCursor(Cursor cursor) {
1246    return new Scan().withStartRow(cursor.getRow());
1247  }
1248
1249  /**
1250   * Enables region level scan metrics. If scan metrics are disabled then first enables scan metrics
1251   * followed by region level scan metrics.
1252   * @param enable Set to true to enable region level scan metrics.
1253   */
1254  public Scan setEnableScanMetricsByRegion(final boolean enable) {
1255    if (enable) {
1256      setScanMetricsEnabled(true);
1257    }
1258    setAttribute(Scan.SCAN_ATTRIBUTES_METRICS_BY_REGION_ENABLE, Bytes.toBytes(enable));
1259    return this;
1260  }
1261
1262  public boolean isScanMetricsByRegionEnabled() {
1263    byte[] attr = getAttribute(Scan.SCAN_ATTRIBUTES_METRICS_BY_REGION_ENABLE);
1264    return attr != null && Bytes.toBoolean(attr);
1265  }
1266}