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 org.apache.hadoop.classification.InterfaceAudience;
23  import org.apache.hadoop.classification.InterfaceStability;
24  import org.apache.hadoop.hbase.HConstants;
25  import org.apache.hadoop.hbase.filter.Filter;
26  import org.apache.hadoop.hbase.filter.IncompatibleFilterException;
27  import org.apache.hadoop.hbase.io.TimeRange;
28  import org.apache.hadoop.hbase.util.Bytes;
29  
30  import java.io.IOException;
31  import java.util.ArrayList;
32  import java.util.HashMap;
33  import java.util.List;
34  import java.util.Map;
35  import java.util.NavigableSet;
36  import java.util.TreeMap;
37  import java.util.TreeSet;
38  
39  /**
40   * Used to perform Scan operations.
41   * <p>
42   * All operations are identical to {@link Get} with the exception of
43   * instantiation.  Rather than specifying a single row, an optional startRow
44   * and stopRow may be defined.  If rows are not specified, the Scanner will
45   * iterate over all rows.
46   * <p>
47   * To scan everything for each row, instantiate a Scan object.
48   * <p>
49   * To modify scanner caching for just this scan, use {@link #setCaching(int) setCaching}.
50   * If caching is NOT set, we will use the caching value of the hosting {@link HTable}.  See
51   * {@link HTable#setScannerCaching(int)}. In addition to row caching, it is possible to specify a
52   * maximum result size, using {@link #setMaxResultSize(long)}. When both are used,
53   * single server requests are limited by either number of rows or maximum result size, whichever
54   * limit comes first.
55   * <p>
56   * To further define the scope of what to get when scanning, perform additional
57   * methods as outlined below.
58   * <p>
59   * To get all columns from specific families, execute {@link #addFamily(byte[]) addFamily}
60   * for each family to retrieve.
61   * <p>
62   * To get specific columns, execute {@link #addColumn(byte[], byte[]) addColumn}
63   * for each column to retrieve.
64   * <p>
65   * To only retrieve columns within a specific range of version timestamps,
66   * execute {@link #setTimeRange(long, long) setTimeRange}.
67   * <p>
68   * To only retrieve columns with a specific timestamp, execute
69   * {@link #setTimeStamp(long) setTimestamp}.
70   * <p>
71   * To limit the number of versions of each column to be returned, execute
72   * {@link #setMaxVersions(int) setMaxVersions}.
73   * <p>
74   * To limit the maximum number of values returned for each call to next(),
75   * execute {@link #setBatch(int) setBatch}.
76   * <p>
77   * To add a filter, execute {@link #setFilter(org.apache.hadoop.hbase.filter.Filter) setFilter}.
78   * <p>
79   * Expert: To explicitly disable server-side block caching for this scan,
80   * execute {@link #setCacheBlocks(boolean)}.
81   */
82  @InterfaceAudience.Public
83  @InterfaceStability.Stable
84  public class Scan extends OperationWithAttributes {
85    private static final String RAW_ATTR = "_raw_";
86    private static final String ISOLATION_LEVEL = "_isolationlevel_";
87  
88    private byte [] startRow = HConstants.EMPTY_START_ROW;
89    private byte [] stopRow  = HConstants.EMPTY_END_ROW;
90    private int maxVersions = 1;
91    private int batch = -1;
92  
93    private int storeLimit = -1;
94    private int storeOffset = 0;
95    private boolean getScan;
96  
97    // If application wants to collect scan metrics, it needs to
98    // call scan.setAttribute(SCAN_ATTRIBUTES_ENABLE, Bytes.toBytes(Boolean.TRUE))
99    static public final String SCAN_ATTRIBUTES_METRICS_ENABLE = "scan.attributes.metrics.enable";
100   static public final String SCAN_ATTRIBUTES_METRICS_DATA = "scan.attributes.metrics.data";
101   
102   // If an application wants to use multiple scans over different tables each scan must
103   // define this attribute with the appropriate table name by calling
104   // scan.setAttribute(Scan.SCAN_ATTRIBUTES_TABLE_NAME, Bytes.toBytes(tableName))
105   static public final String SCAN_ATTRIBUTES_TABLE_NAME = "scan.attributes.table.name";
106   
107   /*
108    * -1 means no caching
109    */
110   private int caching = -1;
111   private long maxResultSize = -1;
112   private boolean cacheBlocks = true;
113   private Filter filter = null;
114   private TimeRange tr = new TimeRange();
115   private Map<byte [], NavigableSet<byte []>> familyMap =
116     new TreeMap<byte [], NavigableSet<byte []>>(Bytes.BYTES_COMPARATOR);
117   private Boolean loadColumnFamiliesOnDemand = null;
118 
119   private boolean prefetching = true;
120 
121   /**
122    * Create a Scan operation across all rows.
123    */
124   public Scan() {}
125 
126   public Scan(byte [] startRow, Filter filter) {
127     this(startRow);
128     this.filter = filter;
129   }
130 
131   /**
132    * Create a Scan operation starting at the specified row.
133    * <p>
134    * If the specified row does not exist, the Scanner will start from the
135    * next closest row after the specified row.
136    * @param startRow row to start scanner at or after
137    */
138   public Scan(byte [] startRow) {
139     this.startRow = startRow;
140   }
141 
142   /**
143    * Create a Scan operation for the range of rows specified.
144    * @param startRow row to start scanner at or after (inclusive)
145    * @param stopRow row to stop scanner before (exclusive)
146    */
147   public Scan(byte [] startRow, byte [] stopRow) {
148     this.startRow = startRow;
149     this.stopRow = stopRow;
150     //if the startRow and stopRow both are empty, it is not a Get
151     this.getScan = isStartRowAndEqualsStopRow();
152   }
153 
154   /**
155    * Creates a new instance of this class while copying all values.
156    *
157    * @param scan  The scan instance to copy from.
158    * @throws IOException When copying the values fails.
159    */
160   public Scan(Scan scan) throws IOException {
161     startRow = scan.getStartRow();
162     stopRow  = scan.getStopRow();
163     maxVersions = scan.getMaxVersions();
164     batch = scan.getBatch();
165     storeLimit = scan.getMaxResultsPerColumnFamily();
166     storeOffset = scan.getRowOffsetPerColumnFamily();
167     caching = scan.getCaching();
168     maxResultSize = scan.getMaxResultSize();
169     cacheBlocks = scan.getCacheBlocks();
170     getScan = scan.isGetScan();
171     filter = scan.getFilter(); // clone?
172     loadColumnFamiliesOnDemand = scan.getLoadColumnFamiliesOnDemandValue();
173     prefetching = scan.getPrefetching();
174     TimeRange ctr = scan.getTimeRange();
175     tr = new TimeRange(ctr.getMin(), ctr.getMax());
176     Map<byte[], NavigableSet<byte[]>> fams = scan.getFamilyMap();
177     for (Map.Entry<byte[],NavigableSet<byte[]>> entry : fams.entrySet()) {
178       byte [] fam = entry.getKey();
179       NavigableSet<byte[]> cols = entry.getValue();
180       if (cols != null && cols.size() > 0) {
181         for (byte[] col : cols) {
182           addColumn(fam, col);
183         }
184       } else {
185         addFamily(fam);
186       }
187     }
188     for (Map.Entry<String, byte[]> attr : scan.getAttributesMap().entrySet()) {
189       setAttribute(attr.getKey(), attr.getValue());
190     }
191   }
192 
193   /**
194    * Builds a scan object with the same specs as get.
195    * @param get get to model scan after
196    */
197   public Scan(Get get) {
198     this.startRow = get.getRow();
199     this.stopRow = get.getRow();
200     this.filter = get.getFilter();
201     this.cacheBlocks = get.getCacheBlocks();
202     this.maxVersions = get.getMaxVersions();
203     this.storeLimit = get.getMaxResultsPerColumnFamily();
204     this.storeOffset = get.getRowOffsetPerColumnFamily();
205     this.tr = get.getTimeRange();
206     this.familyMap = get.getFamilyMap();
207     this.prefetching = false;
208     this.getScan = true;
209   }
210 
211   public boolean isGetScan() {
212     return this.getScan || isStartRowAndEqualsStopRow();
213   }
214 
215   private boolean isStartRowAndEqualsStopRow() {
216     return this.startRow != null && this.startRow.length > 0 &&
217         Bytes.equals(this.startRow, this.stopRow);
218   }
219   /**
220    * Get all columns from the specified family.
221    * <p>
222    * Overrides previous calls to addColumn for this family.
223    * @param family family name
224    * @return this
225    */
226   public Scan addFamily(byte [] family) {
227     familyMap.remove(family);
228     familyMap.put(family, null);
229     return this;
230   }
231 
232   /**
233    * Get the column from the specified family with the specified qualifier.
234    * <p>
235    * Overrides previous calls to addFamily for this family.
236    * @param family family name
237    * @param qualifier column qualifier
238    * @return this
239    */
240   public Scan addColumn(byte [] family, byte [] qualifier) {
241     NavigableSet<byte []> set = familyMap.get(family);
242     if(set == null) {
243       set = new TreeSet<byte []>(Bytes.BYTES_COMPARATOR);
244     }
245     if (qualifier == null) {
246       qualifier = HConstants.EMPTY_BYTE_ARRAY;
247     }
248     set.add(qualifier);
249     familyMap.put(family, set);
250     return this;
251   }
252 
253   /**
254    * Get versions of columns only within the specified timestamp range,
255    * [minStamp, maxStamp).  Note, default maximum versions to return is 1.  If
256    * your time range spans more than one version and you want all versions
257    * returned, up the number of versions beyond the defaut.
258    * @param minStamp minimum timestamp value, inclusive
259    * @param maxStamp maximum timestamp value, exclusive
260    * @throws IOException if invalid time range
261    * @see #setMaxVersions()
262    * @see #setMaxVersions(int)
263    * @return this
264    */
265   public Scan setTimeRange(long minStamp, long maxStamp)
266   throws IOException {
267     tr = new TimeRange(minStamp, maxStamp);
268     return this;
269   }
270 
271   /**
272    * Get versions of columns with the specified timestamp. Note, default maximum
273    * versions to return is 1.  If your time range spans more than one version
274    * and you want all versions returned, up the number of versions beyond the
275    * defaut.
276    * @param timestamp version timestamp
277    * @see #setMaxVersions()
278    * @see #setMaxVersions(int)
279    * @return this
280    */
281   public Scan setTimeStamp(long timestamp) {
282     try {
283       tr = new TimeRange(timestamp, timestamp+1);
284     } catch(IOException e) {
285       // Will never happen
286     }
287     return this;
288   }
289 
290   /**
291    * Set the start row of the scan.
292    * @param startRow row to start scan on (inclusive)
293    * Note: In order to make startRow exclusive add a trailing 0 byte
294    * @return this
295    */
296   public Scan setStartRow(byte [] startRow) {
297     this.startRow = startRow;
298     return this;
299   }
300 
301   /**
302    * Set the stop row.
303    * @param stopRow row to end at (exclusive)
304    * Note: In order to make stopRow inclusive add a trailing 0 byte
305    * @return this
306    */
307   public Scan setStopRow(byte [] stopRow) {
308     this.stopRow = stopRow;
309     return this;
310   }
311 
312   /**
313    * Get all available versions.
314    * @return this
315    */
316   public Scan setMaxVersions() {
317     this.maxVersions = Integer.MAX_VALUE;
318     return this;
319   }
320 
321   /**
322    * Get up to the specified number of versions of each column.
323    * @param maxVersions maximum versions for each column
324    * @return this
325    */
326   public Scan setMaxVersions(int maxVersions) {
327     this.maxVersions = maxVersions;
328     return this;
329   }
330 
331   /**
332    * Set the maximum number of values to return for each call to next()
333    * @param batch the maximum number of values
334    */
335   public void setBatch(int batch) {
336     if (this.hasFilter() && this.filter.hasFilterRow()) {
337       throw new IncompatibleFilterException(
338         "Cannot set batch on a scan using a filter" +
339         " that returns true for filter.hasFilterRow");
340     }
341     this.batch = batch;
342   }
343 
344   /**
345    * Set the maximum number of values to return per row per Column Family
346    * @param limit the maximum number of values returned / row / CF
347    */
348   public void setMaxResultsPerColumnFamily(int limit) {
349     this.storeLimit = limit;
350   }
351 
352   /**
353    * Set offset for the row per Column Family.
354    * @param offset is the number of kvs that will be skipped.
355    */
356   public void setRowOffsetPerColumnFamily(int offset) {
357     this.storeOffset = offset;
358   }
359 
360   /**
361    * Set the number of rows for caching that will be passed to scanners.
362    * If not set, the default setting from {@link HTable#getScannerCaching()} will apply.
363    * Higher caching values will enable faster scanners but will use more memory.
364    * @param caching the number of rows for caching
365    */
366   public void setCaching(int caching) {
367     this.caching = caching;
368   }
369 
370   /**
371    * Set if pre-fetching is enabled. If enabled, the region
372    * server will try to read the next scan result ahead of time. This
373    * improves scan performance if we are doing large scans.
374    *
375    * @param enablePrefetching if pre-fetching is enabled or not
376    */
377   public void setPrefetching(boolean enablePrefetching) {
378     this.prefetching = enablePrefetching;
379   }
380 
381   public boolean getPrefetching() {
382     return prefetching;
383   }
384 
385 /**
386    * @return the maximum result size in bytes. See {@link #setMaxResultSize(long)}
387    */
388   public long getMaxResultSize() {
389     return maxResultSize;
390   }
391 
392   /**
393    * Set the maximum result size. The default is -1; this means that no specific
394    * maximum result size will be set for this scan, and the global configured
395    * value will be used instead. (Defaults to unlimited).
396    *
397    * @param maxResultSize The maximum result size in bytes.
398    */
399   public void setMaxResultSize(long maxResultSize) {
400     this.maxResultSize = maxResultSize;
401   }
402 
403   /**
404    * Apply the specified server-side filter when performing the Scan.
405    * @param filter filter to run on the server
406    * @return this
407    */
408   public Scan setFilter(Filter filter) {
409     this.filter = filter;
410     return this;
411   }
412 
413   /**
414    * Setting the familyMap
415    * @param familyMap map of family to qualifier
416    * @return this
417    */
418   public Scan setFamilyMap(Map<byte [], NavigableSet<byte []>> familyMap) {
419     this.familyMap = familyMap;
420     return this;
421   }
422 
423   /**
424    * Getting the familyMap
425    * @return familyMap
426    */
427   public Map<byte [], NavigableSet<byte []>> getFamilyMap() {
428     return this.familyMap;
429   }
430 
431   /**
432    * @return the number of families in familyMap
433    */
434   public int numFamilies() {
435     if(hasFamilies()) {
436       return this.familyMap.size();
437     }
438     return 0;
439   }
440 
441   /**
442    * @return true if familyMap is non empty, false otherwise
443    */
444   public boolean hasFamilies() {
445     return !this.familyMap.isEmpty();
446   }
447 
448   /**
449    * @return the keys of the familyMap
450    */
451   public byte[][] getFamilies() {
452     if(hasFamilies()) {
453       return this.familyMap.keySet().toArray(new byte[0][0]);
454     }
455     return null;
456   }
457 
458   /**
459    * @return the startrow
460    */
461   public byte [] getStartRow() {
462     return this.startRow;
463   }
464 
465   /**
466    * @return the stoprow
467    */
468   public byte [] getStopRow() {
469     return this.stopRow;
470   }
471 
472   /**
473    * @return the max number of versions to fetch
474    */
475   public int getMaxVersions() {
476     return this.maxVersions;
477   }
478 
479   /**
480    * @return maximum number of values to return for a single call to next()
481    */
482   public int getBatch() {
483     return this.batch;
484   }
485 
486   /**
487    * @return maximum number of values to return per row per CF
488    */
489   public int getMaxResultsPerColumnFamily() {
490     return this.storeLimit;
491   }
492 
493   /**
494    * Method for retrieving the scan's offset per row per column
495    * family (#kvs to be skipped)
496    * @return row offset
497    */
498   public int getRowOffsetPerColumnFamily() {
499     return this.storeOffset;
500   }
501 
502   /**
503    * @return caching the number of rows fetched when calling next on a scanner
504    */
505   public int getCaching() {
506     return this.caching;
507   }
508 
509   /**
510    * @return TimeRange
511    */
512   public TimeRange getTimeRange() {
513     return this.tr;
514   }
515 
516   /**
517    * @return RowFilter
518    */
519   public Filter getFilter() {
520     return filter;
521   }
522 
523   /**
524    * @return true is a filter has been specified, false if not
525    */
526   public boolean hasFilter() {
527     return filter != null;
528   }
529 
530   /**
531    * Set whether blocks should be cached for this Scan.
532    * <p>
533    * This is true by default.  When true, default settings of the table and
534    * family are used (this will never override caching blocks if the block
535    * cache is disabled for that family or entirely).
536    *
537    * @param cacheBlocks if false, default settings are overridden and blocks
538    * will not be cached
539    */
540   public void setCacheBlocks(boolean cacheBlocks) {
541     this.cacheBlocks = cacheBlocks;
542   }
543 
544   /**
545    * Get whether blocks should be cached for this Scan.
546    * @return true if default caching should be used, false if blocks should not
547    * be cached
548    */
549   public boolean getCacheBlocks() {
550     return cacheBlocks;
551   }
552 
553   /**
554    * Set the value indicating whether loading CFs on demand should be allowed (cluster
555    * default is false). On-demand CF loading doesn't load column families until necessary, e.g.
556    * if you filter on one column, the other column family data will be loaded only for the rows
557    * that are included in result, not all rows like in normal case.
558    * With column-specific filters, like SingleColumnValueFilter w/filterIfMissing == true,
559    * this can deliver huge perf gains when there's a cf with lots of data; however, it can
560    * also lead to some inconsistent results, as follows:
561    * - if someone does a concurrent update to both column families in question you may get a row
562    *   that never existed, e.g. for { rowKey = 5, { cat_videos => 1 }, { video => "my cat" } }
563    *   someone puts rowKey 5 with { cat_videos => 0 }, { video => "my dog" }, concurrent scan
564    *   filtering on "cat_videos == 1" can get { rowKey = 5, { cat_videos => 1 },
565    *   { video => "my dog" } }.
566    * - if there's a concurrent split and you have more than 2 column families, some rows may be
567    *   missing some column families.
568    */
569   public void setLoadColumnFamiliesOnDemand(boolean value) {
570     this.loadColumnFamiliesOnDemand = value;
571   }
572 
573   /**
574    * Get the raw loadColumnFamiliesOnDemand setting; if it's not set, can be null.
575    */
576   public Boolean getLoadColumnFamiliesOnDemandValue() {
577     return this.loadColumnFamiliesOnDemand;
578   }
579 
580   /**
581    * Get the logical value indicating whether on-demand CF loading should be allowed.
582    */
583   public boolean doLoadColumnFamiliesOnDemand() {
584     return (this.loadColumnFamiliesOnDemand != null)
585       && this.loadColumnFamiliesOnDemand.booleanValue();
586   }
587 
588   /**
589    * Compile the table and column family (i.e. schema) information
590    * into a String. Useful for parsing and aggregation by debugging,
591    * logging, and administration tools.
592    * @return Map
593    */
594   @Override
595   public Map<String, Object> getFingerprint() {
596     Map<String, Object> map = new HashMap<String, Object>();
597     List<String> families = new ArrayList<String>();
598     if(this.familyMap.size() == 0) {
599       map.put("families", "ALL");
600       return map;
601     } else {
602       map.put("families", families);
603     }
604     for (Map.Entry<byte [], NavigableSet<byte[]>> entry :
605         this.familyMap.entrySet()) {
606       families.add(Bytes.toStringBinary(entry.getKey()));
607     }
608     return map;
609   }
610 
611   /**
612    * Compile the details beyond the scope of getFingerprint (row, columns,
613    * timestamps, etc.) into a Map along with the fingerprinted information.
614    * Useful for debugging, logging, and administration tools.
615    * @param maxCols a limit on the number of columns output prior to truncation
616    * @return Map
617    */
618   @Override
619   public Map<String, Object> toMap(int maxCols) {
620     // start with the fingerpring map and build on top of it
621     Map<String, Object> map = getFingerprint();
622     // map from families to column list replaces fingerprint's list of families
623     Map<String, List<String>> familyColumns =
624       new HashMap<String, List<String>>();
625     map.put("families", familyColumns);
626     // add scalar information first
627     map.put("startRow", Bytes.toStringBinary(this.startRow));
628     map.put("stopRow", Bytes.toStringBinary(this.stopRow));
629     map.put("maxVersions", this.maxVersions);
630     map.put("batch", this.batch);
631     map.put("caching", this.caching);
632     map.put("maxResultSize", this.maxResultSize);
633     map.put("cacheBlocks", this.cacheBlocks);
634     map.put("loadColumnFamiliesOnDemand", this.loadColumnFamiliesOnDemand);
635     map.put("prefetching", this.prefetching);
636     List<Long> timeRange = new ArrayList<Long>();
637     timeRange.add(this.tr.getMin());
638     timeRange.add(this.tr.getMax());
639     map.put("timeRange", timeRange);
640     int colCount = 0;
641     // iterate through affected families and list out up to maxCols columns
642     for (Map.Entry<byte [], NavigableSet<byte[]>> entry :
643       this.familyMap.entrySet()) {
644       List<String> columns = new ArrayList<String>();
645       familyColumns.put(Bytes.toStringBinary(entry.getKey()), columns);
646       if(entry.getValue() == null) {
647         colCount++;
648         --maxCols;
649         columns.add("ALL");
650       } else {
651         colCount += entry.getValue().size();
652         if (maxCols <= 0) {
653           continue;
654         } 
655         for (byte [] column : entry.getValue()) {
656           if (--maxCols <= 0) {
657             continue;
658           }
659           columns.add(Bytes.toStringBinary(column));
660         }
661       } 
662     }       
663     map.put("totalColumns", colCount);
664     if (this.filter != null) {
665       map.put("filter", this.filter.toString());
666     }
667     // add the id if set
668     if (getId() != null) {
669       map.put("id", getId());
670     }
671     return map;
672   }
673 
674   /**
675    * Enable/disable "raw" mode for this scan.
676    * If "raw" is enabled the scan will return all
677    * delete marker and deleted rows that have not
678    * been collected, yet.
679    * This is mostly useful for Scan on column families
680    * that have KEEP_DELETED_ROWS enabled.
681    * It is an error to specify any column when "raw" is set.
682    * @param raw True/False to enable/disable "raw" mode.
683    */
684   public void setRaw(boolean raw) {
685     setAttribute(RAW_ATTR, Bytes.toBytes(raw));
686   }
687 
688   /**
689    * @return True if this Scan is in "raw" mode.
690    */
691   public boolean isRaw() {
692     byte[] attr = getAttribute(RAW_ATTR);
693     return attr == null ? false : Bytes.toBoolean(attr);
694   }
695 
696   /*
697    * Set the isolation level for this scan. If the
698    * isolation level is set to READ_UNCOMMITTED, then
699    * this scan will return data from committed and
700    * uncommitted transactions. If the isolation level 
701    * is set to READ_COMMITTED, then this scan will return 
702    * data from committed transactions only. If a isolation
703    * level is not explicitly set on a Scan, then it 
704    * is assumed to be READ_COMMITTED.
705    * @param level IsolationLevel for this scan
706    */
707   public void setIsolationLevel(IsolationLevel level) {
708     setAttribute(ISOLATION_LEVEL, level.toBytes());
709   }
710   /*
711    * @return The isolation level of this scan.
712    * If no isolation level was set for this scan object, 
713    * then it returns READ_COMMITTED.
714    * @return The IsolationLevel for this scan
715    */
716   public IsolationLevel getIsolationLevel() {
717     byte[] attr = getAttribute(ISOLATION_LEVEL);
718     return attr == null ? IsolationLevel.READ_COMMITTED :
719                           IsolationLevel.fromBytes(attr);
720   }
721 }