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     reversed = scan.isReversed();
231     asyncPrefetch = scan.isAsyncPrefetch();
232     small = scan.isSmall();
233     allowPartialResults = scan.getAllowPartialResults();
234     TimeRange ctr = scan.getTimeRange();
235     tr = new TimeRange(ctr.getMin(), ctr.getMax());
236     Map<byte[], NavigableSet<byte[]>> fams = scan.getFamilyMap();
237     for (Map.Entry<byte[],NavigableSet<byte[]>> entry : fams.entrySet()) {
238       byte [] fam = entry.getKey();
239       NavigableSet<byte[]> cols = entry.getValue();
240       if (cols != null && cols.size() > 0) {
241         for (byte[] col : cols) {
242           addColumn(fam, col);
243         }
244       } else {
245         addFamily(fam);
246       }
247     }
248     for (Map.Entry<String, byte[]> attr : scan.getAttributesMap().entrySet()) {
249       setAttribute(attr.getKey(), attr.getValue());
250     }
251   }
252 
253   /**
254    * Builds a scan object with the same specs as get.
255    * @param get get to model scan after
256    */
257   public Scan(Get get) {
258     this.startRow = get.getRow();
259     this.stopRow = get.getRow();
260     this.filter = get.getFilter();
261     this.cacheBlocks = get.getCacheBlocks();
262     this.maxVersions = get.getMaxVersions();
263     this.storeLimit = get.getMaxResultsPerColumnFamily();
264     this.storeOffset = get.getRowOffsetPerColumnFamily();
265     this.tr = get.getTimeRange();
266     this.familyMap = get.getFamilyMap();
267     this.getScan = true;
268     this.asyncPrefetch = false;
269     this.consistency = get.getConsistency();
270     for (Map.Entry<String, byte[]> attr : get.getAttributesMap().entrySet()) {
271       setAttribute(attr.getKey(), attr.getValue());
272     }
273   }
274 
275   public boolean isGetScan() {
276     return this.getScan || isStartRowAndEqualsStopRow();
277   }
278 
279   private boolean isStartRowAndEqualsStopRow() {
280     return this.startRow != null && this.startRow.length > 0 &&
281         Bytes.equals(this.startRow, this.stopRow);
282   }
283   /**
284    * Get all columns from the specified family.
285    * <p>
286    * Overrides previous calls to addColumn for this family.
287    * @param family family name
288    * @return this
289    */
290   public Scan addFamily(byte [] family) {
291     familyMap.remove(family);
292     familyMap.put(family, null);
293     return this;
294   }
295 
296   /**
297    * Get the column from the specified family with the specified qualifier.
298    * <p>
299    * Overrides previous calls to addFamily for this family.
300    * @param family family name
301    * @param qualifier column qualifier
302    * @return this
303    */
304   public Scan addColumn(byte [] family, byte [] qualifier) {
305     NavigableSet<byte []> set = familyMap.get(family);
306     if(set == null) {
307       set = new TreeSet<byte []>(Bytes.BYTES_COMPARATOR);
308     }
309     if (qualifier == null) {
310       qualifier = HConstants.EMPTY_BYTE_ARRAY;
311     }
312     set.add(qualifier);
313     familyMap.put(family, set);
314     return this;
315   }
316 
317   /**
318    * Get versions of columns only within the specified timestamp range,
319    * [minStamp, maxStamp).  Note, default maximum versions to return is 1.  If
320    * your time range spans more than one version and you want all versions
321    * returned, up the number of versions beyond the default.
322    * @param minStamp minimum timestamp value, inclusive
323    * @param maxStamp maximum timestamp value, exclusive
324    * @throws IOException if invalid time range
325    * @see #setMaxVersions()
326    * @see #setMaxVersions(int)
327    * @return this
328    */
329   public Scan setTimeRange(long minStamp, long maxStamp)
330   throws IOException {
331     tr = new TimeRange(minStamp, maxStamp);
332     return this;
333   }
334 
335   /**
336    * Get versions of columns with the specified timestamp. Note, default maximum
337    * versions to return is 1.  If your time range spans more than one version
338    * and you want all versions returned, up the number of versions beyond the
339    * defaut.
340    * @param timestamp version timestamp
341    * @see #setMaxVersions()
342    * @see #setMaxVersions(int)
343    * @return this
344    */
345   public Scan setTimeStamp(long timestamp)
346   throws IOException {
347     try {
348       tr = new TimeRange(timestamp, timestamp+1);
349     } catch(IOException e) {
350       // This should never happen, unless integer overflow or something extremely wrong...
351       LOG.error("TimeRange failed, likely caused by integer overflow. ", e);
352       throw e;
353     }
354     return this;
355   }
356 
357   /**
358    * Set the start row of the scan.
359    * <p>
360    * If the specified row does not exist, the Scanner will start from the
361    * next closest row after the specified row.
362    * @param startRow row to start scanner at or after
363    * @return this
364    */
365   public Scan setStartRow(byte [] startRow) {
366     this.startRow = startRow;
367     return this;
368   }
369 
370   /**
371    * Set the stop row of the scan.
372    * @param stopRow row to end at (exclusive)
373    * <p>
374    * The scan will include rows that are lexicographically less than
375    * the provided stopRow.
376    * <p><b>Note:</b> When doing a filter for a rowKey <u>Prefix</u>
377    * use {@link #setRowPrefixFilter(byte[])}.
378    * The 'trailing 0' will not yield the desired result.</p>
379    * @return this
380    */
381   public Scan setStopRow(byte [] stopRow) {
382     this.stopRow = stopRow;
383     return this;
384   }
385 
386   /**
387    * <p>Set a filter (using stopRow and startRow) so the result set only contains rows where the
388    * rowKey starts with the specified prefix.</p>
389    * <p>This is a utility method that converts the desired rowPrefix into the appropriate values
390    * for the startRow and stopRow to achieve the desired result.</p>
391    * <p>This can safely be used in combination with setFilter.</p>
392    * <p><b>NOTE: Doing a {@link #setStartRow(byte[])} and/or {@link #setStopRow(byte[])}
393    * after this method will yield undefined results.</b></p>
394    * @param rowPrefix the prefix all rows must start with. (Set <i>null</i> to remove the filter.)
395    * @return this
396    */
397   public Scan setRowPrefixFilter(byte[] rowPrefix) {
398     if (rowPrefix == null) {
399       setStartRow(HConstants.EMPTY_START_ROW);
400       setStopRow(HConstants.EMPTY_END_ROW);
401     } else {
402       this.setStartRow(rowPrefix);
403       this.setStopRow(calculateTheClosestNextRowKeyForPrefix(rowPrefix));
404     }
405     return this;
406   }
407 
408   /**
409    * <p>When scanning for a prefix the scan should stop immediately after the the last row that
410    * has the specified prefix. This method calculates the closest next rowKey immediately following
411    * the given rowKeyPrefix.</p>
412    * <p><b>IMPORTANT: This converts a rowKey<u>Prefix</u> into a rowKey</b>.</p>
413    * <p>If the prefix is an 'ASCII' string put into a byte[] then this is easy because you can
414    * simply increment the last byte of the array.
415    * But if your application uses real binary rowids you may run into the scenario that your
416    * prefix is something like:</p>
417    * &nbsp;&nbsp;&nbsp;<b>{ 0x12, 0x23, 0xFF, 0xFF }</b><br/>
418    * Then this stopRow needs to be fed into the actual scan<br/>
419    * &nbsp;&nbsp;&nbsp;<b>{ 0x12, 0x24 }</b> (Notice that it is shorter now)<br/>
420    * This method calculates the correct stop row value for this usecase.
421    *
422    * @param rowKeyPrefix the rowKey<u>Prefix</u>.
423    * @return the closest next rowKey immediately following the given rowKeyPrefix.
424    */
425   private byte[] calculateTheClosestNextRowKeyForPrefix(byte[] rowKeyPrefix) {
426     // Essentially we are treating it like an 'unsigned very very long' and doing +1 manually.
427     // Search for the place where the trailing 0xFFs start
428     int offset = rowKeyPrefix.length;
429     while (offset > 0) {
430       if (rowKeyPrefix[offset - 1] != (byte) 0xFF) {
431         break;
432       }
433       offset--;
434     }
435 
436     if (offset == 0) {
437       // We got an 0xFFFF... (only FFs) stopRow value which is
438       // the last possible prefix before the end of the table.
439       // So set it to stop at the 'end of the table'
440       return HConstants.EMPTY_END_ROW;
441     }
442 
443     // Copy the right length of the original
444     byte[] newStopRow = Arrays.copyOfRange(rowKeyPrefix, 0, offset);
445     // And increment the last one
446     newStopRow[newStopRow.length - 1]++;
447     return newStopRow;
448   }
449 
450   /**
451    * Get all available versions.
452    * @return this
453    */
454   public Scan setMaxVersions() {
455     this.maxVersions = Integer.MAX_VALUE;
456     return this;
457   }
458 
459   /**
460    * Get up to the specified number of versions of each column.
461    * @param maxVersions maximum versions for each column
462    * @return this
463    */
464   public Scan setMaxVersions(int maxVersions) {
465     this.maxVersions = maxVersions;
466     return this;
467   }
468 
469   /**
470    * Set the maximum number of values to return for each call to next()
471    * @param batch the maximum number of values
472    */
473   public Scan setBatch(int batch) {
474     if (this.hasFilter() && this.filter.hasFilterRow()) {
475       throw new IncompatibleFilterException(
476         "Cannot set batch on a scan using a filter" +
477         " that returns true for filter.hasFilterRow");
478     }
479     this.batch = batch;
480     return this;
481   }
482 
483   /**
484    * Set the maximum number of values to return per row per Column Family
485    * @param limit the maximum number of values returned / row / CF
486    */
487   public Scan setMaxResultsPerColumnFamily(int limit) {
488     this.storeLimit = limit;
489     return this;
490   }
491 
492   /**
493    * Set offset for the row per Column Family.
494    * @param offset is the number of kvs that will be skipped.
495    */
496   public Scan setRowOffsetPerColumnFamily(int offset) {
497     this.storeOffset = offset;
498     return this;
499   }
500 
501   /**
502    * Set the number of rows for caching that will be passed to scanners.
503    * If not set, the Configuration setting {@link HConstants#HBASE_CLIENT_SCANNER_CACHING} will
504    * apply.
505    * Higher caching values will enable faster scanners but will use more memory.
506    * @param caching the number of rows for caching
507    */
508   public Scan setCaching(int caching) {
509     this.caching = caching;
510     return this;
511   }
512 
513   /**
514    * @return the maximum result size in bytes. See {@link #setMaxResultSize(long)}
515    */
516   public long getMaxResultSize() {
517     return maxResultSize;
518   }
519 
520   /**
521    * Set the maximum result size. The default is -1; this means that no specific
522    * maximum result size will be set for this scan, and the global configured
523    * value will be used instead. (Defaults to unlimited).
524    *
525    * @param maxResultSize The maximum result size in bytes.
526    */
527   public Scan setMaxResultSize(long maxResultSize) {
528     this.maxResultSize = maxResultSize;
529     return this;
530   }
531 
532   @Override
533   public Scan setFilter(Filter filter) {
534     super.setFilter(filter);
535     return this;
536   }
537 
538   /**
539    * Setting the familyMap
540    * @param familyMap map of family to qualifier
541    * @return this
542    */
543   public Scan setFamilyMap(Map<byte [], NavigableSet<byte []>> familyMap) {
544     this.familyMap = familyMap;
545     return this;
546   }
547 
548   /**
549    * Getting the familyMap
550    * @return familyMap
551    */
552   public Map<byte [], NavigableSet<byte []>> getFamilyMap() {
553     return this.familyMap;
554   }
555 
556   /**
557    * @return the number of families in familyMap
558    */
559   public int numFamilies() {
560     if(hasFamilies()) {
561       return this.familyMap.size();
562     }
563     return 0;
564   }
565 
566   /**
567    * @return true if familyMap is non empty, false otherwise
568    */
569   public boolean hasFamilies() {
570     return !this.familyMap.isEmpty();
571   }
572 
573   /**
574    * @return the keys of the familyMap
575    */
576   public byte[][] getFamilies() {
577     if(hasFamilies()) {
578       return this.familyMap.keySet().toArray(new byte[0][0]);
579     }
580     return null;
581   }
582 
583   /**
584    * @return the startrow
585    */
586   public byte [] getStartRow() {
587     return this.startRow;
588   }
589 
590   /**
591    * @return the stoprow
592    */
593   public byte [] getStopRow() {
594     return this.stopRow;
595   }
596 
597   /**
598    * @return the max number of versions to fetch
599    */
600   public int getMaxVersions() {
601     return this.maxVersions;
602   }
603 
604   /**
605    * @return maximum number of values to return for a single call to next()
606    */
607   public int getBatch() {
608     return this.batch;
609   }
610 
611   /**
612    * @return maximum number of values to return per row per CF
613    */
614   public int getMaxResultsPerColumnFamily() {
615     return this.storeLimit;
616   }
617 
618   /**
619    * Method for retrieving the scan's offset per row per column
620    * family (#kvs to be skipped)
621    * @return row offset
622    */
623   public int getRowOffsetPerColumnFamily() {
624     return this.storeOffset;
625   }
626 
627   /**
628    * @return caching the number of rows fetched when calling next on a scanner
629    */
630   public int getCaching() {
631     return this.caching;
632   }
633 
634   /**
635    * @return TimeRange
636    */
637   public TimeRange getTimeRange() {
638     return this.tr;
639   }
640 
641   /**
642    * @return RowFilter
643    */
644   @Override
645   public Filter getFilter() {
646     return filter;
647   }
648 
649   /**
650    * @return true is a filter has been specified, false if not
651    */
652   public boolean hasFilter() {
653     return filter != null;
654   }
655 
656   /**
657    * Set whether blocks should be cached for this Scan.
658    * <p>
659    * This is true by default.  When true, default settings of the table and
660    * family are used (this will never override caching blocks if the block
661    * cache is disabled for that family or entirely).
662    *
663    * @param cacheBlocks if false, default settings are overridden and blocks
664    * will not be cached
665    */
666   public Scan setCacheBlocks(boolean cacheBlocks) {
667     this.cacheBlocks = cacheBlocks;
668     return this;
669   }
670 
671   /**
672    * Get whether blocks should be cached for this Scan.
673    * @return true if default caching should be used, false if blocks should not
674    * be cached
675    */
676   public boolean getCacheBlocks() {
677     return cacheBlocks;
678   }
679 
680   /**
681    * Set whether this scan is a reversed one
682    * <p>
683    * This is false by default which means forward(normal) scan.
684    *
685    * @param reversed if true, scan will be backward order
686    * @return this
687    */
688   public Scan setReversed(boolean reversed) {
689     this.reversed = reversed;
690     return this;
691   }
692 
693   /**
694    * Get whether this scan is a reversed one.
695    * @return true if backward scan, false if forward(default) scan
696    */
697   public boolean isReversed() {
698     return reversed;
699   }
700 
701   /**
702    * Setting whether the caller wants to see the partial results that may be returned from the
703    * server. By default this value is false and the complete results will be assembled client side
704    * before being delivered to the caller.
705    * @param allowPartialResults
706    * @return this
707    */
708   public Scan setAllowPartialResults(final boolean allowPartialResults) {
709     this.allowPartialResults = allowPartialResults;
710     return this;
711   }
712 
713   /**
714    * @return true when the constructor of this scan understands that the results they will see may
715    *         only represent a partial portion of a row. The entire row would be retrieved by
716    *         subsequent calls to {@link ResultScanner#next()}
717    */
718   public boolean getAllowPartialResults() {
719     return allowPartialResults;
720   }
721 
722   /**
723    * Set the value indicating whether loading CFs on demand should be allowed (cluster
724    * default is false). On-demand CF loading doesn't load column families until necessary, e.g.
725    * if you filter on one column, the other column family data will be loaded only for the rows
726    * that are included in result, not all rows like in normal case.
727    * With column-specific filters, like SingleColumnValueFilter w/filterIfMissing == true,
728    * this can deliver huge perf gains when there's a cf with lots of data; however, it can
729    * also lead to some inconsistent results, as follows:
730    * - if someone does a concurrent update to both column families in question you may get a row
731    *   that never existed, e.g. for { rowKey = 5, { cat_videos =&gt; 1 }, { video =&gt; "my cat" } }
732    *   someone puts rowKey 5 with { cat_videos =&gt; 0 }, { video =&gt; "my dog" }, concurrent scan
733    *   filtering on "cat_videos == 1" can get { rowKey = 5, { cat_videos =&gt; 1 },
734    *   { video =&gt; "my dog" } }.
735    * - if there's a concurrent split and you have more than 2 column families, some rows may be
736    *   missing some column families.
737    */
738   public Scan setLoadColumnFamiliesOnDemand(boolean value) {
739     this.loadColumnFamiliesOnDemand = value;
740     return this;
741   }
742 
743   /**
744    * Get the raw loadColumnFamiliesOnDemand setting; if it's not set, can be null.
745    */
746   public Boolean getLoadColumnFamiliesOnDemandValue() {
747     return this.loadColumnFamiliesOnDemand;
748   }
749 
750   /**
751    * Get the logical value indicating whether on-demand CF loading should be allowed.
752    */
753   public boolean doLoadColumnFamiliesOnDemand() {
754     return (this.loadColumnFamiliesOnDemand != null)
755       && this.loadColumnFamiliesOnDemand.booleanValue();
756   }
757 
758   /**
759    * Compile the table and column family (i.e. schema) information
760    * into a String. Useful for parsing and aggregation by debugging,
761    * logging, and administration tools.
762    * @return Map
763    */
764   @Override
765   public Map<String, Object> getFingerprint() {
766     Map<String, Object> map = new HashMap<String, Object>();
767     List<String> families = new ArrayList<String>();
768     if(this.familyMap.size() == 0) {
769       map.put("families", "ALL");
770       return map;
771     } else {
772       map.put("families", families);
773     }
774     for (Map.Entry<byte [], NavigableSet<byte[]>> entry :
775         this.familyMap.entrySet()) {
776       families.add(Bytes.toStringBinary(entry.getKey()));
777     }
778     return map;
779   }
780 
781   /**
782    * Compile the details beyond the scope of getFingerprint (row, columns,
783    * timestamps, etc.) into a Map along with the fingerprinted information.
784    * Useful for debugging, logging, and administration tools.
785    * @param maxCols a limit on the number of columns output prior to truncation
786    * @return Map
787    */
788   @Override
789   public Map<String, Object> toMap(int maxCols) {
790     // start with the fingerpring map and build on top of it
791     Map<String, Object> map = getFingerprint();
792     // map from families to column list replaces fingerprint's list of families
793     Map<String, List<String>> familyColumns =
794       new HashMap<String, List<String>>();
795     map.put("families", familyColumns);
796     // add scalar information first
797     map.put("startRow", Bytes.toStringBinary(this.startRow));
798     map.put("stopRow", Bytes.toStringBinary(this.stopRow));
799     map.put("maxVersions", this.maxVersions);
800     map.put("batch", this.batch);
801     map.put("caching", this.caching);
802     map.put("maxResultSize", this.maxResultSize);
803     map.put("cacheBlocks", this.cacheBlocks);
804     map.put("loadColumnFamiliesOnDemand", this.loadColumnFamiliesOnDemand);
805     List<Long> timeRange = new ArrayList<Long>();
806     timeRange.add(this.tr.getMin());
807     timeRange.add(this.tr.getMax());
808     map.put("timeRange", timeRange);
809     int colCount = 0;
810     // iterate through affected families and list out up to maxCols columns
811     for (Map.Entry<byte [], NavigableSet<byte[]>> entry :
812       this.familyMap.entrySet()) {
813       List<String> columns = new ArrayList<String>();
814       familyColumns.put(Bytes.toStringBinary(entry.getKey()), columns);
815       if(entry.getValue() == null) {
816         colCount++;
817         --maxCols;
818         columns.add("ALL");
819       } else {
820         colCount += entry.getValue().size();
821         if (maxCols <= 0) {
822           continue;
823         }
824         for (byte [] column : entry.getValue()) {
825           if (--maxCols <= 0) {
826             continue;
827           }
828           columns.add(Bytes.toStringBinary(column));
829         }
830       }
831     }
832     map.put("totalColumns", colCount);
833     if (this.filter != null) {
834       map.put("filter", this.filter.toString());
835     }
836     // add the id if set
837     if (getId() != null) {
838       map.put("id", getId());
839     }
840     return map;
841   }
842 
843   /**
844    * Enable/disable "raw" mode for this scan.
845    * If "raw" is enabled the scan will return all
846    * delete marker and deleted rows that have not
847    * been collected, yet.
848    * This is mostly useful for Scan on column families
849    * that have KEEP_DELETED_ROWS enabled.
850    * It is an error to specify any column when "raw" is set.
851    * @param raw True/False to enable/disable "raw" mode.
852    */
853   public Scan setRaw(boolean raw) {
854     setAttribute(RAW_ATTR, Bytes.toBytes(raw));
855     return this;
856   }
857 
858   /**
859    * @return True if this Scan is in "raw" mode.
860    */
861   public boolean isRaw() {
862     byte[] attr = getAttribute(RAW_ATTR);
863     return attr == null ? false : Bytes.toBoolean(attr);
864   }
865 
866 
867 
868   /**
869    * Set whether this scan is a small scan
870    * <p>
871    * Small scan should use pread and big scan can use seek + read
872    *
873    * seek + read is fast but can cause two problem (1) resource contention (2)
874    * cause too much network io
875    *
876    * [89-fb] Using pread for non-compaction read request
877    * https://issues.apache.org/jira/browse/HBASE-7266
878    *
879    * On the other hand, if setting it true, we would do
880    * openScanner,next,closeScanner in one RPC call. It means the better
881    * performance for small scan. [HBASE-9488].
882    *
883    * Generally, if the scan range is within one data block(64KB), it could be
884    * considered as a small scan.
885    *
886    * @param small
887    */
888   public Scan setSmall(boolean small) {
889     this.small = small;
890     return this;
891   }
892 
893   /**
894    * Get whether this scan is a small scan
895    * @return true if small scan
896    */
897   public boolean isSmall() {
898     return small;
899   }
900 
901   @Override
902   public Scan setAttribute(String name, byte[] value) {
903     return (Scan) super.setAttribute(name, value);
904   }
905 
906   @Override
907   public Scan setId(String id) {
908     return (Scan) super.setId(id);
909   }
910 
911   @Override
912   public Scan setAuthorizations(Authorizations authorizations) {
913     return (Scan) super.setAuthorizations(authorizations);
914   }
915 
916   @Override
917   public Scan setACL(Map<String, Permission> perms) {
918     return (Scan) super.setACL(perms);
919   }
920 
921   @Override
922   public Scan setACL(String user, Permission perms) {
923     return (Scan) super.setACL(user, perms);
924   }
925 
926   @Override
927   public Scan setConsistency(Consistency consistency) {
928     return (Scan) super.setConsistency(consistency);
929   }
930 
931   @Override
932   public Scan setReplicaId(int Id) {
933     return (Scan) super.setReplicaId(Id);
934   }
935 
936   @Override
937   public Scan setIsolationLevel(IsolationLevel level) {
938     return (Scan) super.setIsolationLevel(level);
939   }
940 
941   /**
942    * Enable collection of {@link ScanMetrics}. For advanced users.
943    * @param enabled Set to true to enable accumulating scan metrics
944    */
945   public Scan setScanMetricsEnabled(final boolean enabled) {
946     setAttribute(Scan.SCAN_ATTRIBUTES_METRICS_ENABLE, Bytes.toBytes(Boolean.valueOf(enabled)));
947     return this;
948   }
949 
950   /**
951    * @return True if collection of scan metrics is enabled. For advanced users.
952    */
953   public boolean isScanMetricsEnabled() {
954     byte[] attr = getAttribute(Scan.SCAN_ATTRIBUTES_METRICS_ENABLE);
955     return attr == null ? false : Bytes.toBoolean(attr);
956   }
957 
958   /**
959    * @return Metrics on this Scan, if metrics were enabled.
960    * @see #setScanMetricsEnabled(boolean)
961    */
962   public ScanMetrics getScanMetrics() {
963     byte [] bytes = getAttribute(Scan.SCAN_ATTRIBUTES_METRICS_DATA);
964     if (bytes == null) return null;
965     return ProtobufUtil.toScanMetrics(bytes);
966   }
967 
968   public Boolean isAsyncPrefetch() {
969     return asyncPrefetch;
970   }
971 
972   public Scan setAsyncPrefetch(boolean asyncPrefetch) {
973     this.asyncPrefetch = asyncPrefetch;
974     return this;
975   }
976 }