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