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