View Javadoc

1   /*
2    *
3    * Licensed to the Apache Software Foundation (ASF) under one
4    * or more contributor license agreements.  See the NOTICE file
5    * distributed with this work for additional information
6    * regarding copyright ownership.  The ASF licenses this file
7    * to you under the Apache License, Version 2.0 (the
8    * "License"); you may not use this file except in compliance
9    * with the License.  You may obtain a copy of the License at
10   *
11   *     http://www.apache.org/licenses/LICENSE-2.0
12   *
13   * Unless required by applicable law or agreed to in writing, software
14   * distributed under the License is distributed on an "AS IS" BASIS,
15   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16   * See the License for the specific language governing permissions and
17   * limitations under the License.
18   */
19  
20  package org.apache.hadoop.hbase.client;
21  
22  import java.io.IOException;
23  import java.util.ArrayList;
24  import java.util.Arrays;
25  import java.util.HashMap;
26  import java.util.List;
27  import java.util.Map;
28  import java.util.NavigableSet;
29  import java.util.TreeMap;
30  import java.util.TreeSet;
31  
32  import org.apache.commons.logging.Log;
33  import org.apache.commons.logging.LogFactory;
34  import org.apache.hadoop.hbase.HConstants;
35  import org.apache.hadoop.hbase.classification.InterfaceAudience;
36  import org.apache.hadoop.hbase.classification.InterfaceStability;
37  import org.apache.hadoop.hbase.client.metrics.ScanMetrics;
38  import org.apache.hadoop.hbase.filter.Filter;
39  import org.apache.hadoop.hbase.filter.IncompatibleFilterException;
40  import org.apache.hadoop.hbase.io.TimeRange;
41  import org.apache.hadoop.hbase.protobuf.ProtobufUtil;
42  import org.apache.hadoop.hbase.security.access.Permission;
43  import org.apache.hadoop.hbase.security.visibility.Authorizations;
44  import org.apache.hadoop.hbase.util.Bytes;
45  
46  /**
47   * Used to perform Scan operations.
48   * <p>
49   * All operations are identical to {@link Get} with the exception of
50   * instantiation.  Rather than specifying a single row, an optional startRow
51   * and stopRow may be defined.  If rows are not specified, the Scanner will
52   * iterate over all rows.
53   * <p>
54   * To get all columns from all rows of a Table, create an instance with no constraints; use the
55   * {@link #Scan()} constructor. To constrain the scan to specific column families,
56   * call {@link #addFamily(byte[]) addFamily} for each family to retrieve on your Scan instance.
57   * <p>
58   * To get specific columns, call {@link #addColumn(byte[], byte[]) addColumn}
59   * for each column to retrieve.
60   * <p>
61   * To only retrieve columns within a specific range of version timestamps,
62   * call {@link #setTimeRange(long, long) setTimeRange}.
63   * <p>
64   * To only retrieve columns with a specific timestamp, call
65   * {@link #setTimeStamp(long) setTimestamp}.
66   * <p>
67   * To limit the number of versions of each column to be returned, call
68   * {@link #setMaxVersions(int) setMaxVersions}.
69   * <p>
70   * To limit the maximum number of values returned for each call to next(),
71   * call {@link #setBatch(int) setBatch}.
72   * <p>
73   * To add a filter, call {@link #setFilter(org.apache.hadoop.hbase.filter.Filter) setFilter}.
74   * <p>
75   * Expert: To explicitly disable server-side block caching for this scan,
76   * execute {@link #setCacheBlocks(boolean)}.
77   * <p><em>Note:</em> Usage alters Scan instances. Internally, attributes are updated as the Scan
78   * runs and if enabled, metrics accumulate in the Scan instance. Be aware this is the case when
79   * you go to clone a Scan instance or if you go to reuse a created Scan instance; safer is create
80   * a Scan instance per usage.
81   */
82  @InterfaceAudience.Public
83  @InterfaceStability.Stable
84  public class Scan extends Query {
85    private static final Log LOG = LogFactory.getLog(Scan.class);
86  
87    private static final String RAW_ATTR = "_raw_";
88  
89    private byte [] startRow = HConstants.EMPTY_START_ROW;
90    private byte [] stopRow  = HConstants.EMPTY_END_ROW;
91    private int maxVersions = 1;
92    private int batch = -1;
93  
94    /**
95     * Partial {@link Result}s are {@link Result}s must be combined to form a complete {@link Result}.
96     * The {@link Result}s had to be returned in fragments (i.e. as partials) because the size of the
97     * cells in the row exceeded max result size on the server. Typically partial results will be
98     * combined client side into complete results before being delivered to the caller. However, if
99     * this flag is set, the caller is indicating that they do not mind seeing partial results (i.e.
100    * they understand that the results returned from the Scanner may only represent part of a
101    * particular row). In such a case, any attempt to combine the partials into a complete result on
102    * the client side will be skipped, and the caller will be able to see the exact results returned
103    * from the server.
104    */
105   private boolean allowPartialResults = false;
106 
107   private int storeLimit = -1;
108   private int storeOffset = 0;
109   private boolean getScan;
110 
111   /**
112    * @deprecated since 1.0.0. Use {@link #setScanMetricsEnabled(boolean)}
113    */
114   // Make private or remove.
115   @Deprecated
116   static public final String SCAN_ATTRIBUTES_METRICS_ENABLE = "scan.attributes.metrics.enable";
117 
118   /**
119    * Use {@link #getScanMetrics()}
120    */
121   // Make this private or remove.
122   @Deprecated
123   static public final String SCAN_ATTRIBUTES_METRICS_DATA = "scan.attributes.metrics.data";
124 
125   // If an application wants to use multiple scans over different tables each scan must
126   // define this attribute with the appropriate table name by calling
127   // scan.setAttribute(Scan.SCAN_ATTRIBUTES_TABLE_NAME, Bytes.toBytes(tableName))
128   static public final String SCAN_ATTRIBUTES_TABLE_NAME = "scan.attributes.table.name";
129 
130   /*
131    * -1 means no caching
132    */
133   private int caching = -1;
134   private long maxResultSize = -1;
135   private boolean cacheBlocks = true;
136   private boolean reversed = false;
137   private TimeRange tr = new TimeRange();
138   private Map<byte [], NavigableSet<byte []>> familyMap =
139     new TreeMap<byte [], NavigableSet<byte []>>(Bytes.BYTES_COMPARATOR);
140   private Boolean loadColumnFamiliesOnDemand = null;
141   private Boolean asyncPrefetch = null;
142 
143   /**
144    * Parameter name for client scanner sync/async prefetch toggle.
145    * When using async scanner, prefetching data from the server is done at the background.
146    * The parameter currently won't have any effect in the case that the user has set
147    * Scan#setSmall or Scan#setReversed
148    */
149   public static final String HBASE_CLIENT_SCANNER_ASYNC_PREFETCH =
150       "hbase.client.scanner.async.prefetch";
151 
152   /**
153    * Default value of {@link #HBASE_CLIENT_SCANNER_ASYNC_PREFETCH}.
154    */
155   public static final boolean DEFAULT_HBASE_CLIENT_SCANNER_ASYNC_PREFETCH = false;
156 
157    /**
158    * Set it true for small scan to get better performance
159    *
160    * Small scan should use pread and big scan can use seek + read
161    *
162    * seek + read is fast but can cause two problem (1) resource contention (2)
163    * cause too much network io
164    *
165    * [89-fb] Using pread for non-compaction read request
166    * https://issues.apache.org/jira/browse/HBASE-7266
167    *
168    * On the other hand, if setting it true, we would do
169    * openScanner,next,closeScanner in one RPC call. It means the better
170    * performance for small scan. [HBASE-9488].
171    *
172    * Generally, if the scan range is within one data block(64KB), it could be
173    * considered as a small scan.
174    */
175   private boolean small = false;
176 
177   /**
178    * Create a Scan operation across all rows.
179    */
180   public Scan() {}
181 
182   public Scan(byte [] startRow, Filter filter) {
183     this(startRow);
184     this.filter = filter;
185   }
186 
187   /**
188    * Create a Scan operation starting at the specified row.
189    * <p>
190    * If the specified row does not exist, the Scanner will start from the
191    * next closest row after the specified row.
192    * @param startRow row to start scanner at or after
193    */
194   public Scan(byte [] startRow) {
195     this.startRow = startRow;
196   }
197 
198   /**
199    * Create a Scan operation for the range of rows specified.
200    * @param startRow row to start scanner at or after (inclusive)
201    * @param stopRow row to stop scanner before (exclusive)
202    */
203   public Scan(byte [] startRow, byte [] stopRow) {
204     this.startRow = startRow;
205     this.stopRow = stopRow;
206     //if the startRow and stopRow both are empty, it is not a Get
207     this.getScan = isStartRowAndEqualsStopRow();
208   }
209 
210   /**
211    * Creates a new instance of this class while copying all values.
212    *
213    * @param scan  The scan instance to copy from.
214    * @throws IOException When copying the values fails.
215    */
216   public Scan(Scan scan) throws IOException {
217     startRow = scan.getStartRow();
218     stopRow  = scan.getStopRow();
219     maxVersions = scan.getMaxVersions();
220     batch = scan.getBatch();
221     storeLimit = scan.getMaxResultsPerColumnFamily();
222     storeOffset = scan.getRowOffsetPerColumnFamily();
223     caching = scan.getCaching();
224     maxResultSize = scan.getMaxResultSize();
225     cacheBlocks = scan.getCacheBlocks();
226     getScan = scan.isGetScan();
227     filter = scan.getFilter(); // clone?
228     loadColumnFamiliesOnDemand = scan.getLoadColumnFamiliesOnDemandValue();
229     consistency = scan.getConsistency();
230     this.setIsolationLevel(scan.getIsolationLevel());
231     reversed = scan.isReversed();
232     asyncPrefetch = scan.isAsyncPrefetch();
233     small = scan.isSmall();
234     allowPartialResults = scan.getAllowPartialResults();
235     TimeRange ctr = scan.getTimeRange();
236     tr = new TimeRange(ctr.getMin(), ctr.getMax());
237     Map<byte[], NavigableSet<byte[]>> fams = scan.getFamilyMap();
238     for (Map.Entry<byte[],NavigableSet<byte[]>> entry : fams.entrySet()) {
239       byte [] fam = entry.getKey();
240       NavigableSet<byte[]> cols = entry.getValue();
241       if (cols != null && cols.size() > 0) {
242         for (byte[] col : cols) {
243           addColumn(fam, col);
244         }
245       } else {
246         addFamily(fam);
247       }
248     }
249     for (Map.Entry<String, byte[]> attr : scan.getAttributesMap().entrySet()) {
250       setAttribute(attr.getKey(), attr.getValue());
251     }
252     for (Map.Entry<byte[], TimeRange> entry : scan.getColumnFamilyTimeRange().entrySet()) {
253       TimeRange tr = entry.getValue();
254       setColumnFamilyTimeRange(entry.getKey(), tr.getMin(), tr.getMax());
255     }
256   }
257 
258   /**
259    * Builds a scan object with the same specs as get.
260    * @param get get to model scan after
261    */
262   public Scan(Get get) {
263     this.startRow = get.getRow();
264     this.stopRow = get.getRow();
265     this.filter = get.getFilter();
266     this.cacheBlocks = get.getCacheBlocks();
267     this.maxVersions = get.getMaxVersions();
268     this.storeLimit = get.getMaxResultsPerColumnFamily();
269     this.storeOffset = get.getRowOffsetPerColumnFamily();
270     this.tr = get.getTimeRange();
271     this.familyMap = get.getFamilyMap();
272     this.getScan = true;
273     this.asyncPrefetch = false;
274     this.consistency = get.getConsistency();
275     this.setIsolationLevel(get.getIsolationLevel());
276     for (Map.Entry<String, byte[]> attr : get.getAttributesMap().entrySet()) {
277       setAttribute(attr.getKey(), attr.getValue());
278     }
279     for (Map.Entry<byte[], TimeRange> entry : get.getColumnFamilyTimeRange().entrySet()) {
280       TimeRange tr = entry.getValue();
281       setColumnFamilyTimeRange(entry.getKey(), tr.getMin(), tr.getMax());
282     }
283   }
284 
285   public boolean isGetScan() {
286     return this.getScan || isStartRowAndEqualsStopRow();
287   }
288 
289   private boolean isStartRowAndEqualsStopRow() {
290     return this.startRow != null && this.startRow.length > 0 &&
291         Bytes.equals(this.startRow, this.stopRow);
292   }
293   /**
294    * Get all columns from the specified family.
295    * <p>
296    * Overrides previous calls to addColumn for this family.
297    * @param family family name
298    * @return this
299    */
300   public Scan addFamily(byte [] family) {
301     familyMap.remove(family);
302     familyMap.put(family, null);
303     return this;
304   }
305 
306   /**
307    * Get the column from the specified family with the specified qualifier.
308    * <p>
309    * Overrides previous calls to addFamily for this family.
310    * @param family family name
311    * @param qualifier column qualifier
312    * @return this
313    */
314   public Scan addColumn(byte [] family, byte [] qualifier) {
315     NavigableSet<byte []> set = familyMap.get(family);
316     if(set == null) {
317       set = new TreeSet<byte []>(Bytes.BYTES_COMPARATOR);
318     }
319     if (qualifier == null) {
320       qualifier = HConstants.EMPTY_BYTE_ARRAY;
321     }
322     set.add(qualifier);
323     familyMap.put(family, set);
324     return this;
325   }
326 
327   /**
328    * Get versions of columns only within the specified timestamp range,
329    * [minStamp, maxStamp).  Note, default maximum versions to return is 1.  If
330    * your time range spans more than one version and you want all versions
331    * returned, up the number of versions beyond the default.
332    * @param minStamp minimum timestamp value, inclusive
333    * @param maxStamp maximum timestamp value, exclusive
334    * @see #setMaxVersions()
335    * @see #setMaxVersions(int)
336    * @return this
337    */
338   public Scan setTimeRange(long minStamp, long maxStamp) throws IOException {
339     tr = new TimeRange(minStamp, maxStamp);
340     return this;
341   }
342 
343   /**
344    * Get versions of columns with the specified timestamp. Note, default maximum
345    * versions to return is 1.  If your time range spans more than one version
346    * and you want all versions returned, up the number of versions beyond the
347    * defaut.
348    * @param timestamp version timestamp
349    * @see #setMaxVersions()
350    * @see #setMaxVersions(int)
351    * @return this
352    */
353   public Scan setTimeStamp(long timestamp)
354   throws IOException {
355     try {
356       tr = new TimeRange(timestamp, timestamp+1);
357     } catch(Exception e) {
358       // This should never happen, unless integer overflow or something extremely wrong...
359       LOG.error("TimeRange failed, likely caused by integer overflow. ", e);
360       throw e;
361     }
362     return this;
363   }
364 
365   @Override public Scan setColumnFamilyTimeRange(byte[] cf, long minStamp, long maxStamp) {
366     return (Scan) super.setColumnFamilyTimeRange(cf, minStamp, maxStamp);
367   }
368 
369   /**
370    * Set the start row of the scan.
371    * <p>
372    * If the specified row does not exist, the Scanner will start from the
373    * next closest row after the specified row.
374    * @param startRow row to start scanner at or after
375    * @return this
376    */
377   public Scan setStartRow(byte [] startRow) {
378     this.startRow = startRow;
379     return this;
380   }
381 
382   /**
383    * Set the stop row of the scan.
384    * @param stopRow row to end at (exclusive)
385    * <p>
386    * The scan will include rows that are lexicographically less than
387    * the provided stopRow.
388    * <p><b>Note:</b> When doing a filter for a rowKey <u>Prefix</u>
389    * use {@link #setRowPrefixFilter(byte[])}.
390    * The 'trailing 0' will not yield the desired result.</p>
391    * @return this
392    */
393   public Scan setStopRow(byte [] stopRow) {
394     this.stopRow = stopRow;
395     return this;
396   }
397 
398   /**
399    * <p>Set a filter (using stopRow and startRow) so the result set only contains rows where the
400    * rowKey starts with the specified prefix.</p>
401    * <p>This is a utility method that converts the desired rowPrefix into the appropriate values
402    * for the startRow and stopRow to achieve the desired result.</p>
403    * <p>This can safely be used in combination with setFilter.</p>
404    * <p><b>NOTE: Doing a {@link #setStartRow(byte[])} and/or {@link #setStopRow(byte[])}
405    * after this method will yield undefined results.</b></p>
406    * @param rowPrefix the prefix all rows must start with. (Set <i>null</i> to remove the filter.)
407    * @return this
408    */
409   public Scan setRowPrefixFilter(byte[] rowPrefix) {
410     if (rowPrefix == null) {
411       setStartRow(HConstants.EMPTY_START_ROW);
412       setStopRow(HConstants.EMPTY_END_ROW);
413     } else {
414       this.setStartRow(rowPrefix);
415       this.setStopRow(calculateTheClosestNextRowKeyForPrefix(rowPrefix));
416     }
417     return this;
418   }
419 
420   /**
421    * <p>When scanning for a prefix the scan should stop immediately after the the last row that
422    * has the specified prefix. This method calculates the closest next rowKey immediately following
423    * the given rowKeyPrefix.</p>
424    * <p><b>IMPORTANT: This converts a rowKey<u>Prefix</u> into a rowKey</b>.</p>
425    * <p>If the prefix is an 'ASCII' string put into a byte[] then this is easy because you can
426    * simply increment the last byte of the array.
427    * But if your application uses real binary rowids you may run into the scenario that your
428    * prefix is something like:</p>
429    * &nbsp;&nbsp;&nbsp;<b>{ 0x12, 0x23, 0xFF, 0xFF }</b><br/>
430    * Then this stopRow needs to be fed into the actual scan<br/>
431    * &nbsp;&nbsp;&nbsp;<b>{ 0x12, 0x24 }</b> (Notice that it is shorter now)<br/>
432    * This method calculates the correct stop row value for this usecase.
433    *
434    * @param rowKeyPrefix the rowKey<u>Prefix</u>.
435    * @return the closest next rowKey immediately following the given rowKeyPrefix.
436    */
437   private byte[] calculateTheClosestNextRowKeyForPrefix(byte[] rowKeyPrefix) {
438     // Essentially we are treating it like an 'unsigned very very long' and doing +1 manually.
439     // Search for the place where the trailing 0xFFs start
440     int offset = rowKeyPrefix.length;
441     while (offset > 0) {
442       if (rowKeyPrefix[offset - 1] != (byte) 0xFF) {
443         break;
444       }
445       offset--;
446     }
447 
448     if (offset == 0) {
449       // We got an 0xFFFF... (only FFs) stopRow value which is
450       // the last possible prefix before the end of the table.
451       // So set it to stop at the 'end of the table'
452       return HConstants.EMPTY_END_ROW;
453     }
454 
455     // Copy the right length of the original
456     byte[] newStopRow = Arrays.copyOfRange(rowKeyPrefix, 0, offset);
457     // And increment the last one
458     newStopRow[newStopRow.length - 1]++;
459     return newStopRow;
460   }
461 
462   /**
463    * Get all available versions.
464    * @return this
465    */
466   public Scan setMaxVersions() {
467     this.maxVersions = Integer.MAX_VALUE;
468     return this;
469   }
470 
471   /**
472    * Get up to the specified number of versions of each column.
473    * @param maxVersions maximum versions for each column
474    * @return this
475    */
476   public Scan setMaxVersions(int maxVersions) {
477     this.maxVersions = maxVersions;
478     return this;
479   }
480 
481   /**
482    * Set the maximum number of values to return for each call to next()
483    * @param batch the maximum number of values
484    */
485   public Scan setBatch(int batch) {
486     if (this.hasFilter() && this.filter.hasFilterRow()) {
487       throw new IncompatibleFilterException(
488         "Cannot set batch on a scan using a filter" +
489         " that returns true for filter.hasFilterRow");
490     }
491     this.batch = batch;
492     return this;
493   }
494 
495   /**
496    * Set the maximum number of values to return per row per Column Family
497    * @param limit the maximum number of values returned / row / CF
498    */
499   public Scan setMaxResultsPerColumnFamily(int limit) {
500     this.storeLimit = limit;
501     return this;
502   }
503 
504   /**
505    * Set offset for the row per Column Family.
506    * @param offset is the number of kvs that will be skipped.
507    */
508   public Scan setRowOffsetPerColumnFamily(int offset) {
509     this.storeOffset = offset;
510     return this;
511   }
512 
513   /**
514    * Set the number of rows for caching that will be passed to scanners.
515    * If not set, the Configuration setting {@link HConstants#HBASE_CLIENT_SCANNER_CACHING} will
516    * apply.
517    * Higher caching values will enable faster scanners but will use more memory.
518    * @param caching the number of rows for caching
519    */
520   public Scan setCaching(int caching) {
521     this.caching = caching;
522     return this;
523   }
524 
525   /**
526    * @return the maximum result size in bytes. See {@link #setMaxResultSize(long)}
527    */
528   public long getMaxResultSize() {
529     return maxResultSize;
530   }
531 
532   /**
533    * Set the maximum result size. The default is -1; this means that no specific
534    * maximum result size will be set for this scan, and the global configured
535    * value will be used instead. (Defaults to unlimited).
536    *
537    * @param maxResultSize The maximum result size in bytes.
538    */
539   public Scan setMaxResultSize(long maxResultSize) {
540     this.maxResultSize = maxResultSize;
541     return this;
542   }
543 
544   @Override
545   public Scan setFilter(Filter filter) {
546     super.setFilter(filter);
547     return this;
548   }
549 
550   /**
551    * Setting the familyMap
552    * @param familyMap map of family to qualifier
553    * @return this
554    */
555   public Scan setFamilyMap(Map<byte [], NavigableSet<byte []>> familyMap) {
556     this.familyMap = familyMap;
557     return this;
558   }
559 
560   /**
561    * Getting the familyMap
562    * @return familyMap
563    */
564   public Map<byte [], NavigableSet<byte []>> getFamilyMap() {
565     return this.familyMap;
566   }
567 
568   /**
569    * @return the number of families in familyMap
570    */
571   public int numFamilies() {
572     if(hasFamilies()) {
573       return this.familyMap.size();
574     }
575     return 0;
576   }
577 
578   /**
579    * @return true if familyMap is non empty, false otherwise
580    */
581   public boolean hasFamilies() {
582     return !this.familyMap.isEmpty();
583   }
584 
585   /**
586    * @return the keys of the familyMap
587    */
588   public byte[][] getFamilies() {
589     if(hasFamilies()) {
590       return this.familyMap.keySet().toArray(new byte[0][0]);
591     }
592     return null;
593   }
594 
595   /**
596    * @return the startrow
597    */
598   public byte [] getStartRow() {
599     return this.startRow;
600   }
601 
602   /**
603    * @return the stoprow
604    */
605   public byte [] getStopRow() {
606     return this.stopRow;
607   }
608 
609   /**
610    * @return the max number of versions to fetch
611    */
612   public int getMaxVersions() {
613     return this.maxVersions;
614   }
615 
616   /**
617    * @return maximum number of values to return for a single call to next()
618    */
619   public int getBatch() {
620     return this.batch;
621   }
622 
623   /**
624    * @return maximum number of values to return per row per CF
625    */
626   public int getMaxResultsPerColumnFamily() {
627     return this.storeLimit;
628   }
629 
630   /**
631    * Method for retrieving the scan's offset per row per column
632    * family (#kvs to be skipped)
633    * @return row offset
634    */
635   public int getRowOffsetPerColumnFamily() {
636     return this.storeOffset;
637   }
638 
639   /**
640    * @return caching the number of rows fetched when calling next on a scanner
641    */
642   public int getCaching() {
643     return this.caching;
644   }
645 
646   /**
647    * @return TimeRange
648    */
649   public TimeRange getTimeRange() {
650     return this.tr;
651   }
652 
653   /**
654    * @return RowFilter
655    */
656   @Override
657   public Filter getFilter() {
658     return filter;
659   }
660 
661   /**
662    * @return true is a filter has been specified, false if not
663    */
664   public boolean hasFilter() {
665     return filter != null;
666   }
667 
668   /**
669    * Set whether blocks should be cached for this Scan.
670    * <p>
671    * This is true by default.  When true, default settings of the table and
672    * family are used (this will never override caching blocks if the block
673    * cache is disabled for that family or entirely).
674    *
675    * @param cacheBlocks if false, default settings are overridden and blocks
676    * will not be cached
677    */
678   public Scan setCacheBlocks(boolean cacheBlocks) {
679     this.cacheBlocks = cacheBlocks;
680     return this;
681   }
682 
683   /**
684    * Get whether blocks should be cached for this Scan.
685    * @return true if default caching should be used, false if blocks should not
686    * be cached
687    */
688   public boolean getCacheBlocks() {
689     return cacheBlocks;
690   }
691 
692   /**
693    * Set whether this scan is a reversed one
694    * <p>
695    * This is false by default which means forward(normal) scan.
696    *
697    * @param reversed if true, scan will be backward order
698    * @return this
699    */
700   public Scan setReversed(boolean reversed) {
701     this.reversed = reversed;
702     return this;
703   }
704 
705   /**
706    * Get whether this scan is a reversed one.
707    * @return true if backward scan, false if forward(default) scan
708    */
709   public boolean isReversed() {
710     return reversed;
711   }
712 
713   /**
714    * Setting whether the caller wants to see the partial results that may be returned from the
715    * server. By default this value is false and the complete results will be assembled client side
716    * before being delivered to the caller.
717    * @param allowPartialResults
718    * @return this
719    */
720   public Scan setAllowPartialResults(final boolean allowPartialResults) {
721     this.allowPartialResults = allowPartialResults;
722     return this;
723   }
724 
725   /**
726    * @return true when the constructor of this scan understands that the results they will see may
727    *         only represent a partial portion of a row. The entire row would be retrieved by
728    *         subsequent calls to {@link ResultScanner#next()}
729    */
730   public boolean getAllowPartialResults() {
731     return allowPartialResults;
732   }
733 
734   /**
735    * Set the value indicating whether loading CFs on demand should be allowed (cluster
736    * default is false). On-demand CF loading doesn't load column families until necessary, e.g.
737    * if you filter on one column, the other column family data will be loaded only for the rows
738    * that are included in result, not all rows like in normal case.
739    * With column-specific filters, like SingleColumnValueFilter w/filterIfMissing == true,
740    * this can deliver huge perf gains when there's a cf with lots of data; however, it can
741    * also lead to some inconsistent results, as follows:
742    * - if someone does a concurrent update to both column families in question you may get a row
743    *   that never existed, e.g. for { rowKey = 5, { cat_videos =&gt; 1 }, { video =&gt; "my cat" } }
744    *   someone puts rowKey 5 with { cat_videos =&gt; 0 }, { video =&gt; "my dog" }, concurrent scan
745    *   filtering on "cat_videos == 1" can get { rowKey = 5, { cat_videos =&gt; 1 },
746    *   { video =&gt; "my dog" } }.
747    * - if there's a concurrent split and you have more than 2 column families, some rows may be
748    *   missing some column families.
749    */
750   public Scan setLoadColumnFamiliesOnDemand(boolean value) {
751     this.loadColumnFamiliesOnDemand = value;
752     return this;
753   }
754 
755   /**
756    * Get the raw loadColumnFamiliesOnDemand setting; if it's not set, can be null.
757    */
758   public Boolean getLoadColumnFamiliesOnDemandValue() {
759     return this.loadColumnFamiliesOnDemand;
760   }
761 
762   /**
763    * Get the logical value indicating whether on-demand CF loading should be allowed.
764    */
765   public boolean doLoadColumnFamiliesOnDemand() {
766     return (this.loadColumnFamiliesOnDemand != null)
767       && this.loadColumnFamiliesOnDemand.booleanValue();
768   }
769 
770   /**
771    * Compile the table and column family (i.e. schema) information
772    * into a String. Useful for parsing and aggregation by debugging,
773    * logging, and administration tools.
774    * @return Map
775    */
776   @Override
777   public Map<String, Object> getFingerprint() {
778     Map<String, Object> map = new HashMap<String, Object>();
779     List<String> families = new ArrayList<String>();
780     if(this.familyMap.size() == 0) {
781       map.put("families", "ALL");
782       return map;
783     } else {
784       map.put("families", families);
785     }
786     for (Map.Entry<byte [], NavigableSet<byte[]>> entry :
787         this.familyMap.entrySet()) {
788       families.add(Bytes.toStringBinary(entry.getKey()));
789     }
790     return map;
791   }
792 
793   /**
794    * Compile the details beyond the scope of getFingerprint (row, columns,
795    * timestamps, etc.) into a Map along with the fingerprinted information.
796    * Useful for debugging, logging, and administration tools.
797    * @param maxCols a limit on the number of columns output prior to truncation
798    * @return Map
799    */
800   @Override
801   public Map<String, Object> toMap(int maxCols) {
802     // start with the fingerpring map and build on top of it
803     Map<String, Object> map = getFingerprint();
804     // map from families to column list replaces fingerprint's list of families
805     Map<String, List<String>> familyColumns =
806       new HashMap<String, List<String>>();
807     map.put("families", familyColumns);
808     // add scalar information first
809     map.put("startRow", Bytes.toStringBinary(this.startRow));
810     map.put("stopRow", Bytes.toStringBinary(this.stopRow));
811     map.put("maxVersions", this.maxVersions);
812     map.put("batch", this.batch);
813     map.put("caching", this.caching);
814     map.put("maxResultSize", this.maxResultSize);
815     map.put("cacheBlocks", this.cacheBlocks);
816     map.put("loadColumnFamiliesOnDemand", this.loadColumnFamiliesOnDemand);
817     List<Long> timeRange = new ArrayList<Long>();
818     timeRange.add(this.tr.getMin());
819     timeRange.add(this.tr.getMax());
820     map.put("timeRange", timeRange);
821     int colCount = 0;
822     // iterate through affected families and list out up to maxCols columns
823     for (Map.Entry<byte [], NavigableSet<byte[]>> entry :
824       this.familyMap.entrySet()) {
825       List<String> columns = new ArrayList<String>();
826       familyColumns.put(Bytes.toStringBinary(entry.getKey()), columns);
827       if(entry.getValue() == null) {
828         colCount++;
829         --maxCols;
830         columns.add("ALL");
831       } else {
832         colCount += entry.getValue().size();
833         if (maxCols <= 0) {
834           continue;
835         }
836         for (byte [] column : entry.getValue()) {
837           if (--maxCols <= 0) {
838             continue;
839           }
840           columns.add(Bytes.toStringBinary(column));
841         }
842       }
843     }
844     map.put("totalColumns", colCount);
845     if (this.filter != null) {
846       map.put("filter", this.filter.toString());
847     }
848     // add the id if set
849     if (getId() != null) {
850       map.put("id", getId());
851     }
852     return map;
853   }
854 
855   /**
856    * Enable/disable "raw" mode for this scan.
857    * If "raw" is enabled the scan will return all
858    * delete marker and deleted rows that have not
859    * been collected, yet.
860    * This is mostly useful for Scan on column families
861    * that have KEEP_DELETED_ROWS enabled.
862    * It is an error to specify any column when "raw" is set.
863    * @param raw True/False to enable/disable "raw" mode.
864    */
865   public Scan setRaw(boolean raw) {
866     setAttribute(RAW_ATTR, Bytes.toBytes(raw));
867     return this;
868   }
869 
870   /**
871    * @return True if this Scan is in "raw" mode.
872    */
873   public boolean isRaw() {
874     byte[] attr = getAttribute(RAW_ATTR);
875     return attr == null ? false : Bytes.toBoolean(attr);
876   }
877 
878 
879 
880   /**
881    * Set whether this scan is a small scan
882    * <p>
883    * Small scan should use pread and big scan can use seek + read
884    *
885    * seek + read is fast but can cause two problem (1) resource contention (2)
886    * cause too much network io
887    *
888    * [89-fb] Using pread for non-compaction read request
889    * https://issues.apache.org/jira/browse/HBASE-7266
890    *
891    * On the other hand, if setting it true, we would do
892    * openScanner,next,closeScanner in one RPC call. It means the better
893    * performance for small scan. [HBASE-9488].
894    *
895    * Generally, if the scan range is within one data block(64KB), it could be
896    * considered as a small scan.
897    *
898    * @param small
899    */
900   public Scan setSmall(boolean small) {
901     this.small = small;
902     return this;
903   }
904 
905   /**
906    * Get whether this scan is a small scan
907    * @return true if small scan
908    */
909   public boolean isSmall() {
910     return small;
911   }
912 
913   @Override
914   public Scan setAttribute(String name, byte[] value) {
915     return (Scan) super.setAttribute(name, value);
916   }
917 
918   @Override
919   public Scan setId(String id) {
920     return (Scan) super.setId(id);
921   }
922 
923   @Override
924   public Scan setAuthorizations(Authorizations authorizations) {
925     return (Scan) super.setAuthorizations(authorizations);
926   }
927 
928   @Override
929   public Scan setACL(Map<String, Permission> perms) {
930     return (Scan) super.setACL(perms);
931   }
932 
933   @Override
934   public Scan setACL(String user, Permission perms) {
935     return (Scan) super.setACL(user, perms);
936   }
937 
938   @Override
939   public Scan setConsistency(Consistency consistency) {
940     return (Scan) super.setConsistency(consistency);
941   }
942 
943   @Override
944   public Scan setReplicaId(int Id) {
945     return (Scan) super.setReplicaId(Id);
946   }
947 
948   @Override
949   public Scan setIsolationLevel(IsolationLevel level) {
950     return (Scan) super.setIsolationLevel(level);
951   }
952 
953   /**
954    * Enable collection of {@link ScanMetrics}. For advanced users.
955    * @param enabled Set to true to enable accumulating scan metrics
956    */
957   public Scan setScanMetricsEnabled(final boolean enabled) {
958     setAttribute(Scan.SCAN_ATTRIBUTES_METRICS_ENABLE, Bytes.toBytes(Boolean.valueOf(enabled)));
959     return this;
960   }
961 
962   /**
963    * @return True if collection of scan metrics is enabled. For advanced users.
964    */
965   public boolean isScanMetricsEnabled() {
966     byte[] attr = getAttribute(Scan.SCAN_ATTRIBUTES_METRICS_ENABLE);
967     return attr == null ? false : Bytes.toBoolean(attr);
968   }
969 
970   /**
971    * @return Metrics on this Scan, if metrics were enabled.
972    * @see #setScanMetricsEnabled(boolean)
973    */
974   public ScanMetrics getScanMetrics() {
975     byte [] bytes = getAttribute(Scan.SCAN_ATTRIBUTES_METRICS_DATA);
976     if (bytes == null) return null;
977     return ProtobufUtil.toScanMetrics(bytes);
978   }
979 
980   public Boolean isAsyncPrefetch() {
981     return asyncPrefetch;
982   }
983 
984   public Scan setAsyncPrefetch(boolean asyncPrefetch) {
985     this.asyncPrefetch = asyncPrefetch;
986     return this;
987   }
988 }