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    * Callers should be aware that invoking this method with any value
484    * is equivalent to calling {@link #setAllowPartialResults(boolean)}
485    * with a value of {@code true}; partial results may be returned if
486    * this method is called. Use {@link #setMaxResultSize(long)}} to
487    * limit the size of a Scan's Results instead.
488    *
489    * @param batch the maximum number of values
490    */
491   public Scan setBatch(int batch) {
492     if (this.hasFilter() && this.filter.hasFilterRow()) {
493       throw new IncompatibleFilterException(
494         "Cannot set batch on a scan using a filter" +
495         " that returns true for filter.hasFilterRow");
496     }
497     this.batch = batch;
498     return this;
499   }
500
501   /**
502    * Set the maximum number of values to return per row per Column Family
503    * @param limit the maximum number of values returned / row / CF
504    */
505   public Scan setMaxResultsPerColumnFamily(int limit) {
506     this.storeLimit = limit;
507     return this;
508   }
509
510   /**
511    * Set offset for the row per Column Family.
512    * @param offset is the number of kvs that will be skipped.
513    */
514   public Scan setRowOffsetPerColumnFamily(int offset) {
515     this.storeOffset = offset;
516     return this;
517   }
518
519   /**
520    * Set the number of rows for caching that will be passed to scanners.
521    * If not set, the Configuration setting {@link HConstants#HBASE_CLIENT_SCANNER_CACHING} will
522    * apply.
523    * Higher caching values will enable faster scanners but will use more memory.
524    * @param caching the number of rows for caching
525    */
526   public Scan setCaching(int caching) {
527     this.caching = caching;
528     return this;
529   }
530
531   /**
532    * @return the maximum result size in bytes. See {@link #setMaxResultSize(long)}
533    */
534   public long getMaxResultSize() {
535     return maxResultSize;
536   }
537
538   /**
539    * Set the maximum result size. The default is -1; this means that no specific
540    * maximum result size will be set for this scan, and the global configured
541    * value will be used instead. (Defaults to unlimited).
542    *
543    * @param maxResultSize The maximum result size in bytes.
544    */
545   public Scan setMaxResultSize(long maxResultSize) {
546     this.maxResultSize = maxResultSize;
547     return this;
548   }
549 
550   @Override
551   public Scan setFilter(Filter filter) {
552     super.setFilter(filter);
553     return this;
554   }
555
556   /**
557    * Setting the familyMap
558    * @param familyMap map of family to qualifier
559    * @return this
560    */
561   public Scan setFamilyMap(Map<byte [], NavigableSet<byte []>> familyMap) {
562     this.familyMap = familyMap;
563     return this;
564   }
565
566   /**
567    * Getting the familyMap
568    * @return familyMap
569    */
570   public Map<byte [], NavigableSet<byte []>> getFamilyMap() {
571     return this.familyMap;
572   }
573
574   /**
575    * @return the number of families in familyMap
576    */
577   public int numFamilies() {
578     if(hasFamilies()) {
579       return this.familyMap.size();
580     }
581     return 0;
582   }
583
584   /**
585    * @return true if familyMap is non empty, false otherwise
586    */
587   public boolean hasFamilies() {
588     return !this.familyMap.isEmpty();
589   }
590
591   /**
592    * @return the keys of the familyMap
593    */
594   public byte[][] getFamilies() {
595     if(hasFamilies()) {
596       return this.familyMap.keySet().toArray(new byte[0][0]);
597     }
598     return null;
599   }
600
601   /**
602    * @return the startrow
603    */
604   public byte [] getStartRow() {
605     return this.startRow;
606   }
607
608   /**
609    * @return the stoprow
610    */
611   public byte [] getStopRow() {
612     return this.stopRow;
613   }
614
615   /**
616    * @return the max number of versions to fetch
617    */
618   public int getMaxVersions() {
619     return this.maxVersions;
620   }
621
622   /**
623    * @return maximum number of values to return for a single call to next()
624    */
625   public int getBatch() {
626     return this.batch;
627   }
628
629   /**
630    * @return maximum number of values to return per row per CF
631    */
632   public int getMaxResultsPerColumnFamily() {
633     return this.storeLimit;
634   }
635
636   /**
637    * Method for retrieving the scan's offset per row per column
638    * family (#kvs to be skipped)
639    * @return row offset
640    */
641   public int getRowOffsetPerColumnFamily() {
642     return this.storeOffset;
643   }
644
645   /**
646    * @return caching the number of rows fetched when calling next on a scanner
647    */
648   public int getCaching() {
649     return this.caching;
650   }
651
652   /**
653    * @return TimeRange
654    */
655   public TimeRange getTimeRange() {
656     return this.tr;
657   }
658
659   /**
660    * @return RowFilter
661    */
662   @Override
663   public Filter getFilter() {
664     return filter;
665   }
666
667   /**
668    * @return true is a filter has been specified, false if not
669    */
670   public boolean hasFilter() {
671     return filter != null;
672   }
673
674   /**
675    * Set whether blocks should be cached for this Scan.
676    * <p>
677    * This is true by default.  When true, default settings of the table and
678    * family are used (this will never override caching blocks if the block
679    * cache is disabled for that family or entirely).
680    *
681    * @param cacheBlocks if false, default settings are overridden and blocks
682    * will not be cached
683    */
684   public Scan setCacheBlocks(boolean cacheBlocks) {
685     this.cacheBlocks = cacheBlocks;
686     return this;
687   }
688
689   /**
690    * Get whether blocks should be cached for this Scan.
691    * @return true if default caching should be used, false if blocks should not
692    * be cached
693    */
694   public boolean getCacheBlocks() {
695     return cacheBlocks;
696   }
697
698   /**
699    * Set whether this scan is a reversed one
700    * <p>
701    * This is false by default which means forward(normal) scan.
702    *
703    * @param reversed if true, scan will be backward order
704    * @return this
705    */
706   public Scan setReversed(boolean reversed) {
707     this.reversed = reversed;
708     return this;
709   }
710
711   /**
712    * Get whether this scan is a reversed one.
713    * @return true if backward scan, false if forward(default) scan
714    */
715   public boolean isReversed() {
716     return reversed;
717   }
718
719   /**
720    * Setting whether the caller wants to see the partial results that may be returned from the
721    * server. By default this value is false and the complete results will be assembled client side
722    * before being delivered to the caller.
723    * @param allowPartialResults
724    * @return this
725    */
726   public Scan setAllowPartialResults(final boolean allowPartialResults) {
727     this.allowPartialResults = allowPartialResults;
728     return this;
729   }
730
731   /**
732    * @return true when the constructor of this scan understands that the results they will see may
733    *         only represent a partial portion of a row. The entire row would be retrieved by
734    *         subsequent calls to {@link ResultScanner#next()}
735    */
736   public boolean getAllowPartialResults() {
737     return allowPartialResults;
738   }
739
740   /**
741    * Set the value indicating whether loading CFs on demand should be allowed (cluster
742    * default is false). On-demand CF loading doesn't load column families until necessary, e.g.
743    * if you filter on one column, the other column family data will be loaded only for the rows
744    * that are included in result, not all rows like in normal case.
745    * With column-specific filters, like SingleColumnValueFilter w/filterIfMissing == true,
746    * this can deliver huge perf gains when there's a cf with lots of data; however, it can
747    * also lead to some inconsistent results, as follows:
748    * - if someone does a concurrent update to both column families in question you may get a row
749    *   that never existed, e.g. for { rowKey = 5, { cat_videos =&gt; 1 }, { video =&gt; "my cat" } }
750    *   someone puts rowKey 5 with { cat_videos =&gt; 0 }, { video =&gt; "my dog" }, concurrent scan
751    *   filtering on "cat_videos == 1" can get { rowKey = 5, { cat_videos =&gt; 1 },
752    *   { video =&gt; "my dog" } }.
753    * - if there's a concurrent split and you have more than 2 column families, some rows may be
754    *   missing some column families.
755    */
756   public Scan setLoadColumnFamiliesOnDemand(boolean value) {
757     this.loadColumnFamiliesOnDemand = value;
758     return this;
759   }
760
761   /**
762    * Get the raw loadColumnFamiliesOnDemand setting; if it's not set, can be null.
763    */
764   public Boolean getLoadColumnFamiliesOnDemandValue() {
765     return this.loadColumnFamiliesOnDemand;
766   }
767
768   /**
769    * Get the logical value indicating whether on-demand CF loading should be allowed.
770    */
771   public boolean doLoadColumnFamiliesOnDemand() {
772     return (this.loadColumnFamiliesOnDemand != null)
773       && this.loadColumnFamiliesOnDemand.booleanValue();
774   }
775
776   /**
777    * Compile the table and column family (i.e. schema) information
778    * into a String. Useful for parsing and aggregation by debugging,
779    * logging, and administration tools.
780    * @return Map
781    */
782   @Override
783   public Map<String, Object> getFingerprint() {
784     Map<String, Object> map = new HashMap<String, Object>();
785     List<String> families = new ArrayList<String>();
786     if(this.familyMap.size() == 0) {
787       map.put("families", "ALL");
788       return map;
789     } else {
790       map.put("families", families);
791     }
792     for (Map.Entry<byte [], NavigableSet<byte[]>> entry :
793         this.familyMap.entrySet()) {
794       families.add(Bytes.toStringBinary(entry.getKey()));
795     }
796     return map;
797   }
798
799   /**
800    * Compile the details beyond the scope of getFingerprint (row, columns,
801    * timestamps, etc.) into a Map along with the fingerprinted information.
802    * Useful for debugging, logging, and administration tools.
803    * @param maxCols a limit on the number of columns output prior to truncation
804    * @return Map
805    */
806   @Override
807   public Map<String, Object> toMap(int maxCols) {
808     // start with the fingerpring map and build on top of it
809     Map<String, Object> map = getFingerprint();
810     // map from families to column list replaces fingerprint's list of families
811     Map<String, List<String>> familyColumns =
812       new HashMap<String, List<String>>();
813     map.put("families", familyColumns);
814     // add scalar information first
815     map.put("startRow", Bytes.toStringBinary(this.startRow));
816     map.put("stopRow", Bytes.toStringBinary(this.stopRow));
817     map.put("maxVersions", this.maxVersions);
818     map.put("batch", this.batch);
819     map.put("caching", this.caching);
820     map.put("maxResultSize", this.maxResultSize);
821     map.put("cacheBlocks", this.cacheBlocks);
822     map.put("loadColumnFamiliesOnDemand", this.loadColumnFamiliesOnDemand);
823     List<Long> timeRange = new ArrayList<Long>();
824     timeRange.add(this.tr.getMin());
825     timeRange.add(this.tr.getMax());
826     map.put("timeRange", timeRange);
827     int colCount = 0;
828     // iterate through affected families and list out up to maxCols columns
829     for (Map.Entry<byte [], NavigableSet<byte[]>> entry :
830       this.familyMap.entrySet()) {
831       List<String> columns = new ArrayList<String>();
832       familyColumns.put(Bytes.toStringBinary(entry.getKey()), columns);
833       if(entry.getValue() == null) {
834         colCount++;
835         --maxCols;
836         columns.add("ALL");
837       } else {
838         colCount += entry.getValue().size();
839         if (maxCols <= 0) {
840           continue;
841         }
842         for (byte [] column : entry.getValue()) {
843           if (--maxCols <= 0) {
844             continue;
845           }
846           columns.add(Bytes.toStringBinary(column));
847         }
848       }
849     }
850     map.put("totalColumns", colCount);
851     if (this.filter != null) {
852       map.put("filter", this.filter.toString());
853     }
854     // add the id if set
855     if (getId() != null) {
856       map.put("id", getId());
857     }
858     return map;
859   }
860
861   /**
862    * Enable/disable "raw" mode for this scan.
863    * If "raw" is enabled the scan will return all
864    * delete marker and deleted rows that have not
865    * been collected, yet.
866    * This is mostly useful for Scan on column families
867    * that have KEEP_DELETED_ROWS enabled.
868    * It is an error to specify any column when "raw" is set.
869    * @param raw True/False to enable/disable "raw" mode.
870    */
871   public Scan setRaw(boolean raw) {
872     setAttribute(RAW_ATTR, Bytes.toBytes(raw));
873     return this;
874   }
875
876   /**
877    * @return True if this Scan is in "raw" mode.
878    */
879   public boolean isRaw() {
880     byte[] attr = getAttribute(RAW_ATTR);
881     return attr == null ? false : Bytes.toBoolean(attr);
882   }
883
884
885
886   /**
887    * Set whether this scan is a small scan
888    * <p>
889    * Small scan should use pread and big scan can use seek + read
890    *
891    * seek + read is fast but can cause two problem (1) resource contention (2)
892    * cause too much network io
893    *
894    * [89-fb] Using pread for non-compaction read request
895    * https://issues.apache.org/jira/browse/HBASE-7266
896    *
897    * On the other hand, if setting it true, we would do
898    * openScanner,next,closeScanner in one RPC call. It means the better
899    * performance for small scan. [HBASE-9488].
900    *
901    * Generally, if the scan range is within one data block(64KB), it could be
902    * considered as a small scan.
903    *
904    * @param small
905    */
906   public Scan setSmall(boolean small) {
907     this.small = small;
908     return this;
909   }
910
911   /**
912    * Get whether this scan is a small scan
913    * @return true if small scan
914    */
915   public boolean isSmall() {
916     return small;
917   }
918
919   @Override
920   public Scan setAttribute(String name, byte[] value) {
921     return (Scan) super.setAttribute(name, value);
922   }
923
924   @Override
925   public Scan setId(String id) {
926     return (Scan) super.setId(id);
927   }
928
929   @Override
930   public Scan setAuthorizations(Authorizations authorizations) {
931     return (Scan) super.setAuthorizations(authorizations);
932   }
933
934   @Override
935   public Scan setACL(Map<String, Permission> perms) {
936     return (Scan) super.setACL(perms);
937   }
938
939   @Override
940   public Scan setACL(String user, Permission perms) {
941     return (Scan) super.setACL(user, perms);
942   }
943
944   @Override
945   public Scan setConsistency(Consistency consistency) {
946     return (Scan) super.setConsistency(consistency);
947   }
948
949   @Override
950   public Scan setReplicaId(int Id) {
951     return (Scan) super.setReplicaId(Id);
952   }
953
954   @Override
955   public Scan setIsolationLevel(IsolationLevel level) {
956     return (Scan) super.setIsolationLevel(level);
957   }
958
959   /**
960    * Enable collection of {@link ScanMetrics}. For advanced users.
961    * @param enabled Set to true to enable accumulating scan metrics
962    */
963   public Scan setScanMetricsEnabled(final boolean enabled) {
964     setAttribute(Scan.SCAN_ATTRIBUTES_METRICS_ENABLE, Bytes.toBytes(Boolean.valueOf(enabled)));
965     return this;
966   }
967
968   /**
969    * @return True if collection of scan metrics is enabled. For advanced users.
970    */
971   public boolean isScanMetricsEnabled() {
972     byte[] attr = getAttribute(Scan.SCAN_ATTRIBUTES_METRICS_ENABLE);
973     return attr == null ? false : Bytes.toBoolean(attr);
974   }
975
976   /**
977    * @return Metrics on this Scan, if metrics were enabled.
978    * @see #setScanMetricsEnabled(boolean)
979    */
980   public ScanMetrics getScanMetrics() {
981     byte [] bytes = getAttribute(Scan.SCAN_ATTRIBUTES_METRICS_DATA);
982     if (bytes == null) return null;
983     return ProtobufUtil.toScanMetrics(bytes);
984   }
985
986   public Boolean isAsyncPrefetch() {
987     return asyncPrefetch;
988   }
989
990   public Scan setAsyncPrefetch(boolean asyncPrefetch) {
991     this.asyncPrefetch = asyncPrefetch;
992     return this;
993   }
994 }