001/* 002 * Licensed to the Apache Software Foundation (ASF) under one 003 * or more contributor license agreements. See the NOTICE file 004 * distributed with this work for additional information 005 * regarding copyright ownership. The ASF licenses this file 006 * to you under the Apache License, Version 2.0 (the 007 * "License"); you may not use this file except in compliance 008 * with the License. You may obtain a copy of the License at 009 * 010 * http://www.apache.org/licenses/LICENSE-2.0 011 * 012 * Unless required by applicable law or agreed to in writing, software 013 * distributed under the License is distributed on an "AS IS" BASIS, 014 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 015 * See the License for the specific language governing permissions and 016 * limitations under the License. 017 */ 018package org.apache.hadoop.hbase.client; 019 020import java.io.IOException; 021import java.util.ArrayList; 022import java.util.HashMap; 023import java.util.List; 024import java.util.Map; 025import java.util.NavigableSet; 026import java.util.TreeMap; 027import java.util.TreeSet; 028import java.util.stream.Collectors; 029import org.apache.hadoop.hbase.HConstants; 030import org.apache.hadoop.hbase.client.metrics.ScanMetrics; 031import org.apache.hadoop.hbase.filter.Filter; 032import org.apache.hadoop.hbase.filter.IncompatibleFilterException; 033import org.apache.hadoop.hbase.io.TimeRange; 034import org.apache.hadoop.hbase.security.access.Permission; 035import org.apache.hadoop.hbase.security.visibility.Authorizations; 036import org.apache.hadoop.hbase.util.Bytes; 037import org.apache.yetus.audience.InterfaceAudience; 038import org.slf4j.Logger; 039import org.slf4j.LoggerFactory; 040 041import org.apache.hadoop.hbase.shaded.protobuf.ProtobufUtil; 042 043/** 044 * Used to perform Scan operations. 045 * <p> 046 * All operations are identical to {@link Get} with the exception of instantiation. Rather than 047 * specifying a single row, an optional startRow and stopRow may be defined. If rows are not 048 * specified, the Scanner will iterate over all rows. 049 * <p> 050 * To get all columns from all rows of a Table, create an instance with no constraints; use the 051 * {@link #Scan()} constructor. To constrain the scan to specific column families, call 052 * {@link #addFamily(byte[]) addFamily} for each family to retrieve on your Scan instance. 053 * <p> 054 * To get specific columns, call {@link #addColumn(byte[], byte[]) addColumn} for each column to 055 * retrieve. 056 * <p> 057 * To only retrieve columns within a specific range of version timestamps, call 058 * {@link #setTimeRange(long, long) setTimeRange}. 059 * <p> 060 * To only retrieve columns with a specific timestamp, call {@link #setTimestamp(long) setTimestamp} 061 * . 062 * <p> 063 * To limit the number of versions of each column to be returned, call {@link #setMaxVersions(int) 064 * setMaxVersions}. 065 * <p> 066 * To limit the maximum number of values returned for each call to next(), call 067 * {@link #setBatch(int) setBatch}. 068 * <p> 069 * To add a filter, call {@link #setFilter(org.apache.hadoop.hbase.filter.Filter) setFilter}. 070 * <p> 071 * For small scan, it is deprecated in 2.0.0. Now we have a {@link #setLimit(int)} method in Scan 072 * object which is used to tell RS how many rows we want. If the rows return reaches the limit, the 073 * RS will close the RegionScanner automatically. And we will also fetch data when openScanner in 074 * the new implementation, this means we can also finish a scan operation in one rpc call. And we 075 * have also introduced a {@link #setReadType(ReadType)} method. You can use this method to tell RS 076 * to use pread explicitly. 077 * <p> 078 * Expert: To explicitly disable server-side block caching for this scan, execute 079 * {@link #setCacheBlocks(boolean)}. 080 * <p> 081 * <em>Note:</em> Usage alters Scan instances. Internally, attributes are updated as the Scan runs 082 * and if enabled, metrics accumulate in the Scan instance. Be aware this is the case when you go to 083 * clone a Scan instance or if you go to reuse a created Scan instance; safer is create a Scan 084 * instance per usage. 085 */ 086@InterfaceAudience.Public 087public class Scan extends Query { 088 private static final Logger LOG = LoggerFactory.getLogger(Scan.class); 089 090 private static final String RAW_ATTR = "_raw_"; 091 092 private byte[] startRow = HConstants.EMPTY_START_ROW; 093 private boolean includeStartRow = true; 094 private byte[] stopRow = HConstants.EMPTY_END_ROW; 095 private boolean includeStopRow = false; 096 private int maxVersions = 1; 097 private int batch = -1; 098 099 /** 100 * Partial {@link Result}s are {@link Result}s must be combined to form a complete {@link Result}. 101 * The {@link Result}s had to be returned in fragments (i.e. as partials) because the size of the 102 * cells in the row exceeded max result size on the server. Typically partial results will be 103 * combined client side into complete results before being delivered to the caller. However, if 104 * this flag is set, the caller is indicating that they do not mind seeing partial results (i.e. 105 * they understand that the results returned from the Scanner may only represent part of a 106 * particular row). In such a case, any attempt to combine the partials into a complete result on 107 * the client side will be skipped, and the caller will be able to see the exact results returned 108 * from the server. 109 */ 110 private boolean allowPartialResults = false; 111 112 private int storeLimit = -1; 113 private int storeOffset = 0; 114 115 /** 116 * @deprecated since 1.0.0. Use {@link #setScanMetricsEnabled(boolean)} 117 */ 118 // Make private or remove. 119 @Deprecated 120 static public final String SCAN_ATTRIBUTES_METRICS_ENABLE = "scan.attributes.metrics.enable"; 121 122 /** 123 * Use {@link #getScanMetrics()} 124 */ 125 // Make this private or remove. 126 @Deprecated 127 static public final String SCAN_ATTRIBUTES_METRICS_DATA = "scan.attributes.metrics.data"; 128 129 // If an application wants to use multiple scans over different tables each scan must 130 // define this attribute with the appropriate table name by calling 131 // scan.setAttribute(Scan.SCAN_ATTRIBUTES_TABLE_NAME, Bytes.toBytes(tableName)) 132 static public final String SCAN_ATTRIBUTES_TABLE_NAME = "scan.attributes.table.name"; 133 134 /** 135 * -1 means no caching specified and the value of {@link HConstants#HBASE_CLIENT_SCANNER_CACHING} 136 * (default to {@link HConstants#DEFAULT_HBASE_CLIENT_SCANNER_CACHING}) will be used 137 */ 138 private int caching = -1; 139 private long maxResultSize = -1; 140 private boolean cacheBlocks = true; 141 private boolean reversed = false; 142 private TimeRange tr = TimeRange.allTime(); 143 private Map<byte[], NavigableSet<byte[]>> familyMap = 144 new TreeMap<byte[], NavigableSet<byte[]>>(Bytes.BYTES_COMPARATOR); 145 private Boolean asyncPrefetch = null; 146 147 /** 148 * Parameter name for client scanner sync/async prefetch toggle. When using async scanner, 149 * prefetching data from the server is done at the background. The parameter currently won't have 150 * any effect in the case that the user has set Scan#setSmall or Scan#setReversed 151 */ 152 public static final String HBASE_CLIENT_SCANNER_ASYNC_PREFETCH = 153 "hbase.client.scanner.async.prefetch"; 154 155 /** 156 * Default value of {@link #HBASE_CLIENT_SCANNER_ASYNC_PREFETCH}. 157 */ 158 public static final boolean DEFAULT_HBASE_CLIENT_SCANNER_ASYNC_PREFETCH = false; 159 160 /** 161 * Set it true for small scan to get better performance Small scan should use pread and big scan 162 * can use seek + read seek + read is fast but can cause two problem (1) resource contention (2) 163 * cause too much network io [89-fb] Using pread for non-compaction read request 164 * https://issues.apache.org/jira/browse/HBASE-7266 On the other hand, if setting it true, we 165 * would do openScanner,next,closeScanner in one RPC call. It means the better performance for 166 * small scan. [HBASE-9488]. Generally, if the scan range is within one data block(64KB), it could 167 * be considered as a small scan. 168 */ 169 private boolean small = false; 170 171 /** 172 * The mvcc read point to use when open a scanner. Remember to clear it after switching regions as 173 * the mvcc is only valid within region scope. 174 */ 175 private long mvccReadPoint = -1L; 176 177 /** 178 * The number of rows we want for this scan. We will terminate the scan if the number of return 179 * rows reaches this value. 180 */ 181 private int limit = -1; 182 183 /** 184 * Control whether to use pread at server side. 185 */ 186 private ReadType readType = ReadType.DEFAULT; 187 188 private boolean needCursorResult = false; 189 190 /** 191 * Create a Scan operation across all rows. 192 */ 193 public Scan() { 194 } 195 196 /** 197 * @deprecated since 2.0.0 and will be removed in 3.0.0. Use 198 * {@code new Scan().withStartRow(startRow).setFilter(filter)} instead. 199 * @see <a href="https://issues.apache.org/jira/browse/HBASE-17320">HBASE-17320</a> 200 */ 201 @Deprecated 202 public Scan(byte[] startRow, Filter filter) { 203 this(startRow); 204 this.filter = filter; 205 } 206 207 /** 208 * Create a Scan operation starting at the specified row. 209 * <p> 210 * If the specified row does not exist, the Scanner will start from the next closest row after the 211 * specified row. 212 * @param startRow row to start scanner at or after 213 * @deprecated since 2.0.0 and will be removed in 3.0.0. Use 214 * {@code new Scan().withStartRow(startRow)} instead. 215 * @see <a href="https://issues.apache.org/jira/browse/HBASE-17320">HBASE-17320</a> 216 */ 217 @Deprecated 218 public Scan(byte[] startRow) { 219 setStartRow(startRow); 220 } 221 222 /** 223 * Create a Scan operation for the range of rows specified. 224 * @param startRow row to start scanner at or after (inclusive) 225 * @param stopRow row to stop scanner before (exclusive) 226 * @deprecated since 2.0.0 and will be removed in 3.0.0. Use 227 * {@code new Scan().withStartRow(startRow).withStopRow(stopRow)} instead. 228 * @see <a href="https://issues.apache.org/jira/browse/HBASE-17320">HBASE-17320</a> 229 */ 230 @Deprecated 231 public Scan(byte[] startRow, byte[] stopRow) { 232 setStartRow(startRow); 233 setStopRow(stopRow); 234 } 235 236 /** 237 * Creates a new instance of this class while copying all values. 238 * @param scan The scan instance to copy from. 239 * @throws IOException When copying the values fails. 240 */ 241 public Scan(Scan scan) throws IOException { 242 startRow = scan.getStartRow(); 243 includeStartRow = scan.includeStartRow(); 244 stopRow = scan.getStopRow(); 245 includeStopRow = scan.includeStopRow(); 246 maxVersions = scan.getMaxVersions(); 247 batch = scan.getBatch(); 248 storeLimit = scan.getMaxResultsPerColumnFamily(); 249 storeOffset = scan.getRowOffsetPerColumnFamily(); 250 caching = scan.getCaching(); 251 maxResultSize = scan.getMaxResultSize(); 252 cacheBlocks = scan.getCacheBlocks(); 253 filter = scan.getFilter(); // clone? 254 loadColumnFamiliesOnDemand = scan.getLoadColumnFamiliesOnDemandValue(); 255 consistency = scan.getConsistency(); 256 this.setIsolationLevel(scan.getIsolationLevel()); 257 reversed = scan.isReversed(); 258 asyncPrefetch = scan.isAsyncPrefetch(); 259 small = scan.isSmall(); 260 allowPartialResults = scan.getAllowPartialResults(); 261 tr = scan.getTimeRange(); // TimeRange is immutable 262 Map<byte[], NavigableSet<byte[]>> fams = scan.getFamilyMap(); 263 for (Map.Entry<byte[], NavigableSet<byte[]>> entry : fams.entrySet()) { 264 byte[] fam = entry.getKey(); 265 NavigableSet<byte[]> cols = entry.getValue(); 266 if (cols != null && cols.size() > 0) { 267 for (byte[] col : cols) { 268 addColumn(fam, col); 269 } 270 } else { 271 addFamily(fam); 272 } 273 } 274 for (Map.Entry<String, byte[]> attr : scan.getAttributesMap().entrySet()) { 275 setAttribute(attr.getKey(), attr.getValue()); 276 } 277 for (Map.Entry<byte[], TimeRange> entry : scan.getColumnFamilyTimeRange().entrySet()) { 278 TimeRange tr = entry.getValue(); 279 setColumnFamilyTimeRange(entry.getKey(), tr.getMin(), tr.getMax()); 280 } 281 this.mvccReadPoint = scan.getMvccReadPoint(); 282 this.limit = scan.getLimit(); 283 this.needCursorResult = scan.isNeedCursorResult(); 284 setPriority(scan.getPriority()); 285 readType = scan.getReadType(); 286 super.setReplicaId(scan.getReplicaId()); 287 } 288 289 /** 290 * Builds a scan object with the same specs as get. 291 * @param get get to model scan after 292 */ 293 public Scan(Get get) { 294 this.startRow = get.getRow(); 295 this.includeStartRow = true; 296 this.stopRow = get.getRow(); 297 this.includeStopRow = true; 298 this.filter = get.getFilter(); 299 this.cacheBlocks = get.getCacheBlocks(); 300 this.maxVersions = get.getMaxVersions(); 301 this.storeLimit = get.getMaxResultsPerColumnFamily(); 302 this.storeOffset = get.getRowOffsetPerColumnFamily(); 303 this.tr = get.getTimeRange(); 304 this.familyMap = get.getFamilyMap(); 305 this.asyncPrefetch = false; 306 this.consistency = get.getConsistency(); 307 this.setIsolationLevel(get.getIsolationLevel()); 308 this.loadColumnFamiliesOnDemand = get.getLoadColumnFamiliesOnDemandValue(); 309 for (Map.Entry<String, byte[]> attr : get.getAttributesMap().entrySet()) { 310 setAttribute(attr.getKey(), attr.getValue()); 311 } 312 for (Map.Entry<byte[], TimeRange> entry : get.getColumnFamilyTimeRange().entrySet()) { 313 TimeRange tr = entry.getValue(); 314 setColumnFamilyTimeRange(entry.getKey(), tr.getMin(), tr.getMax()); 315 } 316 this.mvccReadPoint = -1L; 317 setPriority(get.getPriority()); 318 super.setReplicaId(get.getReplicaId()); 319 } 320 321 public boolean isGetScan() { 322 return includeStartRow && includeStopRow 323 && ClientUtil.areScanStartRowAndStopRowEqual(this.startRow, this.stopRow); 324 } 325 326 /** 327 * Get all columns from the specified family. 328 * <p> 329 * Overrides previous calls to addColumn for this family. 330 * @param family family name 331 */ 332 public Scan addFamily(byte[] family) { 333 familyMap.remove(family); 334 familyMap.put(family, null); 335 return this; 336 } 337 338 /** 339 * Get the column from the specified family with the specified qualifier. 340 * <p> 341 * Overrides previous calls to addFamily for this family. 342 * @param family family name 343 * @param qualifier column qualifier 344 */ 345 public Scan addColumn(byte[] family, byte[] qualifier) { 346 NavigableSet<byte[]> set = familyMap.get(family); 347 if (set == null) { 348 set = new TreeSet<>(Bytes.BYTES_COMPARATOR); 349 familyMap.put(family, set); 350 } 351 if (qualifier == null) { 352 qualifier = HConstants.EMPTY_BYTE_ARRAY; 353 } 354 set.add(qualifier); 355 return this; 356 } 357 358 /** 359 * Get versions of columns only within the specified timestamp range, [minStamp, maxStamp). Note, 360 * default maximum versions to return is 1. If your time range spans more than one version and you 361 * want all versions returned, up the number of versions beyond the default. 362 * @param minStamp minimum timestamp value, inclusive 363 * @param maxStamp maximum timestamp value, exclusive 364 * @see #setMaxVersions() 365 * @see #setMaxVersions(int) 366 */ 367 public Scan setTimeRange(long minStamp, long maxStamp) throws IOException { 368 tr = new TimeRange(minStamp, maxStamp); 369 return this; 370 } 371 372 /** 373 * Get versions of columns with the specified timestamp. Note, default maximum versions to return 374 * is 1. If your time range spans more than one version and you want all versions returned, up the 375 * number of versions beyond the defaut. 376 * @param timestamp version timestamp 377 * @see #setMaxVersions() 378 * @see #setMaxVersions(int) 379 * @deprecated As of release 2.0.0, this will be removed in HBase 3.0.0. Use 380 * {@link #setTimestamp(long)} instead 381 */ 382 @Deprecated 383 public Scan setTimeStamp(long timestamp) throws IOException { 384 return this.setTimestamp(timestamp); 385 } 386 387 /** 388 * Get versions of columns with the specified timestamp. Note, default maximum versions to return 389 * is 1. If your time range spans more than one version and you want all versions returned, up the 390 * number of versions beyond the defaut. 391 * @param timestamp version timestamp 392 * @see #setMaxVersions() 393 * @see #setMaxVersions(int) 394 */ 395 public Scan setTimestamp(long timestamp) { 396 try { 397 tr = new TimeRange(timestamp, timestamp + 1); 398 } catch (Exception e) { 399 // This should never happen, unless integer overflow or something extremely wrong... 400 LOG.error("TimeRange failed, likely caused by integer overflow. ", e); 401 throw e; 402 } 403 404 return this; 405 } 406 407 @Override 408 public Scan setColumnFamilyTimeRange(byte[] cf, long minStamp, long maxStamp) { 409 return (Scan) super.setColumnFamilyTimeRange(cf, minStamp, maxStamp); 410 } 411 412 /** 413 * Set the start row of the scan. 414 * <p> 415 * If the specified row does not exist, the Scanner will start from the next closest row after the 416 * specified row. 417 * @param startRow row to start scanner at or after 418 * @throws IllegalArgumentException if startRow does not meet criteria for a row key (when length 419 * exceeds {@link HConstants#MAX_ROW_LENGTH}) 420 * @deprecated since 2.0.0 and will be removed in 3.0.0. Use {@link #withStartRow(byte[])} 421 * instead. This method may change the inclusive of the stop row to keep compatible 422 * with the old behavior. 423 * @see #withStartRow(byte[]) 424 * @see <a href="https://issues.apache.org/jira/browse/HBASE-17320">HBASE-17320</a> 425 */ 426 @Deprecated 427 public Scan setStartRow(byte[] startRow) { 428 withStartRow(startRow); 429 if (ClientUtil.areScanStartRowAndStopRowEqual(this.startRow, this.stopRow)) { 430 // for keeping the old behavior that a scan with the same start and stop row is a get scan. 431 this.includeStopRow = true; 432 } 433 return this; 434 } 435 436 /** 437 * Set the start row of the scan. 438 * <p> 439 * If the specified row does not exist, the Scanner will start from the next closest row after the 440 * specified row. 441 * @param startRow row to start scanner at or after 442 * @throws IllegalArgumentException if startRow does not meet criteria for a row key (when length 443 * exceeds {@link HConstants#MAX_ROW_LENGTH}) 444 */ 445 public Scan withStartRow(byte[] startRow) { 446 return withStartRow(startRow, true); 447 } 448 449 /** 450 * Set the start row of the scan. 451 * <p> 452 * If the specified row does not exist, or the {@code inclusive} is {@code false}, the Scanner 453 * will start from the next closest row after the specified row. 454 * @param startRow row to start scanner at or after 455 * @param inclusive whether we should include the start row when scan 456 * @throws IllegalArgumentException if startRow does not meet criteria for a row key (when length 457 * exceeds {@link HConstants#MAX_ROW_LENGTH}) 458 */ 459 public Scan withStartRow(byte[] startRow, boolean inclusive) { 460 if (Bytes.len(startRow) > HConstants.MAX_ROW_LENGTH) { 461 throw new IllegalArgumentException("startRow's length must be less than or equal to " 462 + HConstants.MAX_ROW_LENGTH + " to meet the criteria" + " for a row key."); 463 } 464 this.startRow = startRow; 465 this.includeStartRow = inclusive; 466 return this; 467 } 468 469 /** 470 * Set the stop row of the scan. 471 * <p> 472 * The scan will include rows that are lexicographically less than the provided stopRow. 473 * <p> 474 * <b>Note:</b> When doing a filter for a rowKey <u>Prefix</u> use 475 * {@link #setRowPrefixFilter(byte[])}. The 'trailing 0' will not yield the desired result. 476 * </p> 477 * @param stopRow row to end at (exclusive) 478 * @throws IllegalArgumentException if stopRow does not meet criteria for a row key (when length 479 * exceeds {@link HConstants#MAX_ROW_LENGTH}) 480 * @deprecated since 2.0.0 and will be removed in 3.0.0. Use {@link #withStopRow(byte[])} instead. 481 * This method may change the inclusive of the stop row to keep compatible with the 482 * old behavior. 483 * @see #withStopRow(byte[]) 484 * @see <a href="https://issues.apache.org/jira/browse/HBASE-17320">HBASE-17320</a> 485 */ 486 @Deprecated 487 public Scan setStopRow(byte[] stopRow) { 488 withStopRow(stopRow); 489 if (ClientUtil.areScanStartRowAndStopRowEqual(this.startRow, this.stopRow)) { 490 // for keeping the old behavior that a scan with the same start and stop row is a get scan. 491 this.includeStopRow = true; 492 } 493 return this; 494 } 495 496 /** 497 * Set the stop row of the scan. 498 * <p> 499 * The scan will include rows that are lexicographically less than the provided stopRow. 500 * <p> 501 * <b>Note:</b> When doing a filter for a rowKey <u>Prefix</u> use 502 * {@link #setRowPrefixFilter(byte[])}. The 'trailing 0' will not yield the desired result. 503 * </p> 504 * @param stopRow row to end at (exclusive) 505 * @throws IllegalArgumentException if stopRow does not meet criteria for a row key (when length 506 * exceeds {@link HConstants#MAX_ROW_LENGTH}) 507 */ 508 public Scan withStopRow(byte[] stopRow) { 509 return withStopRow(stopRow, false); 510 } 511 512 /** 513 * Set the stop row of the scan. 514 * <p> 515 * The scan will include rows that are lexicographically less than (or equal to if 516 * {@code inclusive} is {@code true}) the provided stopRow. 517 * @param stopRow row to end at 518 * @param inclusive whether we should include the stop row when scan 519 * @throws IllegalArgumentException if stopRow does not meet criteria for a row key (when length 520 * exceeds {@link HConstants#MAX_ROW_LENGTH}) 521 */ 522 public Scan withStopRow(byte[] stopRow, boolean inclusive) { 523 if (Bytes.len(stopRow) > HConstants.MAX_ROW_LENGTH) { 524 throw new IllegalArgumentException("stopRow's length must be less than or equal to " 525 + HConstants.MAX_ROW_LENGTH + " to meet the criteria" + " for a row key."); 526 } 527 this.stopRow = stopRow; 528 this.includeStopRow = inclusive; 529 return this; 530 } 531 532 /** 533 * <p> 534 * Set a filter (using stopRow and startRow) so the result set only contains rows where the rowKey 535 * starts with the specified prefix. 536 * </p> 537 * <p> 538 * This is a utility method that converts the desired rowPrefix into the appropriate values for 539 * the startRow and stopRow to achieve the desired result. 540 * </p> 541 * <p> 542 * This can safely be used in combination with setFilter. 543 * </p> 544 * <p> 545 * <b>NOTE: Doing a {@link #setStartRow(byte[])} and/or {@link #setStopRow(byte[])} after this 546 * method will yield undefined results.</b> 547 * </p> 548 * @param rowPrefix the prefix all rows must start with. (Set <i>null</i> to remove the filter.) 549 */ 550 public Scan setRowPrefixFilter(byte[] rowPrefix) { 551 if (rowPrefix == null) { 552 setStartRow(HConstants.EMPTY_START_ROW); 553 setStopRow(HConstants.EMPTY_END_ROW); 554 } else { 555 this.setStartRow(rowPrefix); 556 this.setStopRow(ClientUtil.calculateTheClosestNextRowKeyForPrefix(rowPrefix)); 557 } 558 return this; 559 } 560 561 /** 562 * Get all available versions. 563 * @deprecated since 2.0.0 and will be removed in 3.0.0. It is easy to misunderstand with column 564 * family's max versions, so use {@link #readAllVersions()} instead. 565 * @see #readAllVersions() 566 * @see <a href="https://issues.apache.org/jira/browse/HBASE-17125">HBASE-17125</a> 567 */ 568 @Deprecated 569 public Scan setMaxVersions() { 570 return readAllVersions(); 571 } 572 573 /** 574 * Get up to the specified number of versions of each column. 575 * @param maxVersions maximum versions for each column 576 * @deprecated since 2.0.0 and will be removed in 3.0.0. It is easy to misunderstand with column 577 * family's max versions, so use {@link #readVersions(int)} instead. 578 * @see #readVersions(int) 579 * @see <a href="https://issues.apache.org/jira/browse/HBASE-17125">HBASE-17125</a> 580 */ 581 @Deprecated 582 public Scan setMaxVersions(int maxVersions) { 583 return readVersions(maxVersions); 584 } 585 586 /** 587 * Get all available versions. 588 */ 589 public Scan readAllVersions() { 590 this.maxVersions = Integer.MAX_VALUE; 591 return this; 592 } 593 594 /** 595 * Get up to the specified number of versions of each column. 596 * @param versions specified number of versions for each column 597 */ 598 public Scan readVersions(int versions) { 599 this.maxVersions = versions; 600 return this; 601 } 602 603 /** 604 * Set the maximum number of cells to return for each call to next(). Callers should be aware that 605 * this is not equivalent to calling {@link #setAllowPartialResults(boolean)}. If you don't allow 606 * partial results, the number of cells in each Result must equal to your batch setting unless it 607 * is the last Result for current row. So this method is helpful in paging queries. If you just 608 * want to prevent OOM at client, use setAllowPartialResults(true) is better. 609 * @param batch the maximum number of values 610 * @see Result#mayHaveMoreCellsInRow() 611 */ 612 public Scan setBatch(int batch) { 613 if (this.hasFilter() && this.filter.hasFilterRow()) { 614 throw new IncompatibleFilterException( 615 "Cannot set batch on a scan using a filter" + " that returns true for filter.hasFilterRow"); 616 } 617 this.batch = batch; 618 return this; 619 } 620 621 /** 622 * Set the maximum number of values to return per row per Column Family 623 * @param limit the maximum number of values returned / row / CF 624 */ 625 public Scan setMaxResultsPerColumnFamily(int limit) { 626 this.storeLimit = limit; 627 return this; 628 } 629 630 /** 631 * Set offset for the row per Column Family. 632 * @param offset is the number of kvs that will be skipped. 633 */ 634 public Scan setRowOffsetPerColumnFamily(int offset) { 635 this.storeOffset = offset; 636 return this; 637 } 638 639 /** 640 * Set the number of rows for caching that will be passed to scanners. If not set, the 641 * Configuration setting {@link HConstants#HBASE_CLIENT_SCANNER_CACHING} will apply. Higher 642 * caching values will enable faster scanners but will use more memory. 643 * @param caching the number of rows for caching 644 */ 645 public Scan setCaching(int caching) { 646 this.caching = caching; 647 return this; 648 } 649 650 /** Returns the maximum result size in bytes. See {@link #setMaxResultSize(long)} */ 651 public long getMaxResultSize() { 652 return maxResultSize; 653 } 654 655 /** 656 * Set the maximum result size. The default is -1; this means that no specific maximum result size 657 * will be set for this scan, and the global configured value will be used instead. (Defaults to 658 * unlimited). 659 * @param maxResultSize The maximum result size in bytes. 660 */ 661 public Scan setMaxResultSize(long maxResultSize) { 662 this.maxResultSize = maxResultSize; 663 return this; 664 } 665 666 @Override 667 public Scan setFilter(Filter filter) { 668 super.setFilter(filter); 669 return this; 670 } 671 672 /** 673 * Setting the familyMap 674 * @param familyMap map of family to qualifier 675 */ 676 public Scan setFamilyMap(Map<byte[], NavigableSet<byte[]>> familyMap) { 677 this.familyMap = familyMap; 678 return this; 679 } 680 681 /** 682 * Getting the familyMap 683 */ 684 public Map<byte[], NavigableSet<byte[]>> getFamilyMap() { 685 return this.familyMap; 686 } 687 688 /** Returns the number of families in familyMap */ 689 public int numFamilies() { 690 if (hasFamilies()) { 691 return this.familyMap.size(); 692 } 693 return 0; 694 } 695 696 /** Returns true if familyMap is non empty, false otherwise */ 697 public boolean hasFamilies() { 698 return !this.familyMap.isEmpty(); 699 } 700 701 /** Returns the keys of the familyMap */ 702 public byte[][] getFamilies() { 703 if (hasFamilies()) { 704 return this.familyMap.keySet().toArray(new byte[0][0]); 705 } 706 return null; 707 } 708 709 /** Returns the startrow */ 710 public byte[] getStartRow() { 711 return this.startRow; 712 } 713 714 /** Returns if we should include start row when scan */ 715 public boolean includeStartRow() { 716 return includeStartRow; 717 } 718 719 /** Returns the stoprow */ 720 public byte[] getStopRow() { 721 return this.stopRow; 722 } 723 724 /** Returns if we should include stop row when scan */ 725 public boolean includeStopRow() { 726 return includeStopRow; 727 } 728 729 /** Returns the max number of versions to fetch */ 730 public int getMaxVersions() { 731 return this.maxVersions; 732 } 733 734 /** Returns maximum number of values to return for a single call to next() */ 735 public int getBatch() { 736 return this.batch; 737 } 738 739 /** Returns maximum number of values to return per row per CF */ 740 public int getMaxResultsPerColumnFamily() { 741 return this.storeLimit; 742 } 743 744 /** 745 * Method for retrieving the scan's offset per row per column family (#kvs to be skipped) 746 * @return row offset 747 */ 748 public int getRowOffsetPerColumnFamily() { 749 return this.storeOffset; 750 } 751 752 /** Returns caching the number of rows fetched when calling next on a scanner */ 753 public int getCaching() { 754 return this.caching; 755 } 756 757 /** Returns TimeRange */ 758 public TimeRange getTimeRange() { 759 return this.tr; 760 } 761 762 /** Returns RowFilter */ 763 @Override 764 public Filter getFilter() { 765 return filter; 766 } 767 768 /** Returns true is a filter has been specified, false if not */ 769 public boolean hasFilter() { 770 return filter != null; 771 } 772 773 /** 774 * Set whether blocks should be cached for this Scan. 775 * <p> 776 * This is true by default. When true, default settings of the table and family are used (this 777 * will never override caching blocks if the block cache is disabled for that family or entirely). 778 * @param cacheBlocks if false, default settings are overridden and blocks will not be cached 779 */ 780 public Scan setCacheBlocks(boolean cacheBlocks) { 781 this.cacheBlocks = cacheBlocks; 782 return this; 783 } 784 785 /** 786 * Get whether blocks should be cached for this Scan. 787 * @return true if default caching should be used, false if blocks should not be cached 788 */ 789 public boolean getCacheBlocks() { 790 return cacheBlocks; 791 } 792 793 /** 794 * Set whether this scan is a reversed one 795 * <p> 796 * This is false by default which means forward(normal) scan. 797 * @param reversed if true, scan will be backward order 798 */ 799 public Scan setReversed(boolean reversed) { 800 this.reversed = reversed; 801 return this; 802 } 803 804 /** 805 * Get whether this scan is a reversed one. 806 * @return true if backward scan, false if forward(default) scan 807 */ 808 public boolean isReversed() { 809 return reversed; 810 } 811 812 /** 813 * Setting whether the caller wants to see the partial results when server returns 814 * less-than-expected cells. It is helpful while scanning a huge row to prevent OOM at client. By 815 * default this value is false and the complete results will be assembled client side before being 816 * delivered to the caller. 817 * @see Result#mayHaveMoreCellsInRow() 818 * @see #setBatch(int) 819 */ 820 public Scan setAllowPartialResults(final boolean allowPartialResults) { 821 this.allowPartialResults = allowPartialResults; 822 return this; 823 } 824 825 /** 826 * @return true when the constructor of this scan understands that the results they will see may 827 * only represent a partial portion of a row. The entire row would be retrieved by 828 * subsequent calls to {@link ResultScanner#next()} 829 */ 830 public boolean getAllowPartialResults() { 831 return allowPartialResults; 832 } 833 834 @Override 835 public Scan setLoadColumnFamiliesOnDemand(boolean value) { 836 return (Scan) super.setLoadColumnFamiliesOnDemand(value); 837 } 838 839 /** 840 * Compile the table and column family (i.e. schema) information into a String. Useful for parsing 841 * and aggregation by debugging, logging, and administration tools. 842 */ 843 @Override 844 public Map<String, Object> getFingerprint() { 845 Map<String, Object> map = new HashMap<>(); 846 List<String> families = new ArrayList<>(); 847 if (this.familyMap.isEmpty()) { 848 map.put("families", "ALL"); 849 return map; 850 } else { 851 map.put("families", families); 852 } 853 for (Map.Entry<byte[], NavigableSet<byte[]>> entry : this.familyMap.entrySet()) { 854 families.add(Bytes.toStringBinary(entry.getKey())); 855 } 856 return map; 857 } 858 859 /** 860 * Compile the details beyond the scope of getFingerprint (row, columns, timestamps, etc.) into a 861 * Map along with the fingerprinted information. Useful for debugging, logging, and administration 862 * tools. 863 * @param maxCols a limit on the number of columns output prior to truncation 864 */ 865 @Override 866 public Map<String, Object> toMap(int maxCols) { 867 // start with the fingerprint map and build on top of it 868 Map<String, Object> map = getFingerprint(); 869 // map from families to column list replaces fingerprint's list of families 870 Map<String, List<String>> familyColumns = new HashMap<>(); 871 map.put("families", familyColumns); 872 // add scalar information first 873 map.put("startRow", Bytes.toStringBinary(this.startRow)); 874 map.put("stopRow", Bytes.toStringBinary(this.stopRow)); 875 map.put("maxVersions", this.maxVersions); 876 map.put("batch", this.batch); 877 map.put("caching", this.caching); 878 map.put("maxResultSize", this.maxResultSize); 879 map.put("cacheBlocks", this.cacheBlocks); 880 map.put("loadColumnFamiliesOnDemand", this.loadColumnFamiliesOnDemand); 881 List<Long> timeRange = new ArrayList<>(2); 882 timeRange.add(this.tr.getMin()); 883 timeRange.add(this.tr.getMax()); 884 map.put("timeRange", timeRange); 885 int colCount = 0; 886 // iterate through affected families and list out up to maxCols columns 887 for (Map.Entry<byte[], NavigableSet<byte[]>> entry : this.familyMap.entrySet()) { 888 List<String> columns = new ArrayList<>(); 889 familyColumns.put(Bytes.toStringBinary(entry.getKey()), columns); 890 if (entry.getValue() == null) { 891 colCount++; 892 --maxCols; 893 columns.add("ALL"); 894 } else { 895 colCount += entry.getValue().size(); 896 if (maxCols <= 0) { 897 continue; 898 } 899 for (byte[] column : entry.getValue()) { 900 if (--maxCols <= 0) { 901 continue; 902 } 903 columns.add(Bytes.toStringBinary(column)); 904 } 905 } 906 } 907 map.put("totalColumns", colCount); 908 if (this.filter != null) { 909 map.put("filter", this.filter.toString()); 910 } 911 // add the id if set 912 if (getId() != null) { 913 map.put("id", getId()); 914 } 915 map.put("includeStartRow", includeStartRow); 916 map.put("includeStopRow", includeStopRow); 917 map.put("allowPartialResults", allowPartialResults); 918 map.put("storeLimit", storeLimit); 919 map.put("storeOffset", storeOffset); 920 map.put("reversed", reversed); 921 if (null != asyncPrefetch) { 922 map.put("asyncPrefetch", asyncPrefetch); 923 } 924 map.put("mvccReadPoint", mvccReadPoint); 925 map.put("limit", limit); 926 map.put("readType", readType); 927 map.put("needCursorResult", needCursorResult); 928 map.put("targetReplicaId", targetReplicaId); 929 map.put("consistency", consistency); 930 if (!colFamTimeRangeMap.isEmpty()) { 931 Map<String, List<Long>> colFamTimeRangeMapStr = colFamTimeRangeMap.entrySet().stream() 932 .collect(Collectors.toMap((e) -> Bytes.toStringBinary(e.getKey()), e -> { 933 TimeRange value = e.getValue(); 934 List<Long> rangeList = new ArrayList<>(); 935 rangeList.add(value.getMin()); 936 rangeList.add(value.getMax()); 937 return rangeList; 938 })); 939 940 map.put("colFamTimeRangeMap", colFamTimeRangeMapStr); 941 } 942 map.put("priority", getPriority()); 943 return map; 944 } 945 946 /** 947 * Enable/disable "raw" mode for this scan. If "raw" is enabled the scan will return all delete 948 * marker and deleted rows that have not been collected, yet. This is mostly useful for Scan on 949 * column families that have KEEP_DELETED_ROWS enabled. It is an error to specify any column when 950 * "raw" is set. 951 * @param raw True/False to enable/disable "raw" mode. 952 */ 953 public Scan setRaw(boolean raw) { 954 setAttribute(RAW_ATTR, Bytes.toBytes(raw)); 955 return this; 956 } 957 958 /** Returns True if this Scan is in "raw" mode. */ 959 public boolean isRaw() { 960 byte[] attr = getAttribute(RAW_ATTR); 961 return attr == null ? false : Bytes.toBoolean(attr); 962 } 963 964 /** 965 * Set whether this scan is a small scan 966 * <p> 967 * Small scan should use pread and big scan can use seek + read seek + read is fast but can cause 968 * two problem (1) resource contention (2) cause too much network io [89-fb] Using pread for 969 * non-compaction read request https://issues.apache.org/jira/browse/HBASE-7266 On the other hand, 970 * if setting it true, we would do openScanner,next,closeScanner in one RPC call. It means the 971 * better performance for small scan. [HBASE-9488]. Generally, if the scan range is within one 972 * data block(64KB), it could be considered as a small scan. 973 * @deprecated since 2.0.0 and will be removed in 3.0.0. Use {@link #setLimit(int)} and 974 * {@link #setReadType(ReadType)} instead. And for the one rpc optimization, now we 975 * will also fetch data when openScanner, and if the number of rows reaches the limit 976 * then we will close the scanner automatically which means we will fall back to one 977 * rpc. 978 * @see #setLimit(int) 979 * @see #setReadType(ReadType) 980 * @see <a href="https://issues.apache.org/jira/browse/HBASE-17045">HBASE-17045</a> 981 */ 982 @Deprecated 983 public Scan setSmall(boolean small) { 984 this.small = small; 985 if (small) { 986 this.readType = ReadType.PREAD; 987 } 988 return this; 989 } 990 991 /** 992 * Get whether this scan is a small scan 993 * @return true if small scan 994 * @deprecated since 2.0.0 and will be removed in 3.0.0. See the comment of 995 * {@link #setSmall(boolean)} 996 * @see <a href="https://issues.apache.org/jira/browse/HBASE-17045">HBASE-17045</a> 997 */ 998 @Deprecated 999 public boolean isSmall() { 1000 return small; 1001 } 1002 1003 @Override 1004 public Scan setAttribute(String name, byte[] value) { 1005 return (Scan) super.setAttribute(name, value); 1006 } 1007 1008 @Override 1009 public Scan setId(String id) { 1010 return (Scan) super.setId(id); 1011 } 1012 1013 @Override 1014 public Scan setAuthorizations(Authorizations authorizations) { 1015 return (Scan) super.setAuthorizations(authorizations); 1016 } 1017 1018 @Override 1019 public Scan setACL(Map<String, Permission> perms) { 1020 return (Scan) super.setACL(perms); 1021 } 1022 1023 @Override 1024 public Scan setACL(String user, Permission perms) { 1025 return (Scan) super.setACL(user, perms); 1026 } 1027 1028 @Override 1029 public Scan setConsistency(Consistency consistency) { 1030 return (Scan) super.setConsistency(consistency); 1031 } 1032 1033 @Override 1034 public Scan setReplicaId(int Id) { 1035 return (Scan) super.setReplicaId(Id); 1036 } 1037 1038 @Override 1039 public Scan setIsolationLevel(IsolationLevel level) { 1040 return (Scan) super.setIsolationLevel(level); 1041 } 1042 1043 @Override 1044 public Scan setPriority(int priority) { 1045 return (Scan) super.setPriority(priority); 1046 } 1047 1048 /** 1049 * Enable collection of {@link ScanMetrics}. For advanced users. 1050 * @param enabled Set to true to enable accumulating scan metrics 1051 */ 1052 public Scan setScanMetricsEnabled(final boolean enabled) { 1053 setAttribute(Scan.SCAN_ATTRIBUTES_METRICS_ENABLE, Bytes.toBytes(Boolean.valueOf(enabled))); 1054 return this; 1055 } 1056 1057 /** Returns True if collection of scan metrics is enabled. For advanced users. */ 1058 public boolean isScanMetricsEnabled() { 1059 byte[] attr = getAttribute(Scan.SCAN_ATTRIBUTES_METRICS_ENABLE); 1060 return attr == null ? false : Bytes.toBoolean(attr); 1061 } 1062 1063 /** 1064 * @return Metrics on this Scan, if metrics were enabled. 1065 * @see #setScanMetricsEnabled(boolean) 1066 * @deprecated Use {@link ResultScanner#getScanMetrics()} instead. And notice that, please do not 1067 * use this method and {@link ResultScanner#getScanMetrics()} together, the metrics 1068 * will be messed up. 1069 */ 1070 @Deprecated 1071 public ScanMetrics getScanMetrics() { 1072 byte[] bytes = getAttribute(Scan.SCAN_ATTRIBUTES_METRICS_DATA); 1073 if (bytes == null) return null; 1074 return ProtobufUtil.toScanMetrics(bytes); 1075 } 1076 1077 public Boolean isAsyncPrefetch() { 1078 return asyncPrefetch; 1079 } 1080 1081 public Scan setAsyncPrefetch(boolean asyncPrefetch) { 1082 this.asyncPrefetch = asyncPrefetch; 1083 return this; 1084 } 1085 1086 /** Returns the limit of rows for this scan */ 1087 public int getLimit() { 1088 return limit; 1089 } 1090 1091 /** 1092 * Set the limit of rows for this scan. We will terminate the scan if the number of returned rows 1093 * reaches this value. 1094 * <p> 1095 * This condition will be tested at last, after all other conditions such as stopRow, filter, etc. 1096 * @param limit the limit of rows for this scan 1097 */ 1098 public Scan setLimit(int limit) { 1099 this.limit = limit; 1100 return this; 1101 } 1102 1103 /** 1104 * Call this when you only want to get one row. It will set {@code limit} to {@code 1}, and also 1105 * set {@code readType} to {@link ReadType#PREAD}. 1106 */ 1107 public Scan setOneRowLimit() { 1108 return setLimit(1).setReadType(ReadType.PREAD); 1109 } 1110 1111 @InterfaceAudience.Public 1112 public enum ReadType { 1113 DEFAULT, 1114 STREAM, 1115 PREAD 1116 } 1117 1118 /** Returns the read type for this scan */ 1119 public ReadType getReadType() { 1120 return readType; 1121 } 1122 1123 /** 1124 * Set the read type for this scan. 1125 * <p> 1126 * Notice that we may choose to use pread even if you specific {@link ReadType#STREAM} here. For 1127 * example, we will always use pread if this is a get scan. 1128 */ 1129 public Scan setReadType(ReadType readType) { 1130 this.readType = readType; 1131 return this; 1132 } 1133 1134 /** 1135 * Get the mvcc read point used to open a scanner. 1136 */ 1137 long getMvccReadPoint() { 1138 return mvccReadPoint; 1139 } 1140 1141 /** 1142 * Set the mvcc read point used to open a scanner. 1143 */ 1144 Scan setMvccReadPoint(long mvccReadPoint) { 1145 this.mvccReadPoint = mvccReadPoint; 1146 return this; 1147 } 1148 1149 /** 1150 * Set the mvcc read point to -1 which means do not use it. 1151 */ 1152 Scan resetMvccReadPoint() { 1153 return setMvccReadPoint(-1L); 1154 } 1155 1156 /** 1157 * When the server is slow or we scan a table with many deleted data or we use a sparse filter, 1158 * the server will response heartbeat to prevent timeout. However the scanner will return a Result 1159 * only when client can do it. So if there are many heartbeats, the blocking time on 1160 * ResultScanner#next() may be very long, which is not friendly to online services. Set this to 1161 * true then you can get a special Result whose #isCursor() returns true and is not contains any 1162 * real data. It only tells you where the server has scanned. You can call next to continue 1163 * scanning or open a new scanner with this row key as start row whenever you want. Users can get 1164 * a cursor when and only when there is a response from the server but we can not return a Result 1165 * to users, for example, this response is a heartbeat or there are partial cells but users do not 1166 * allow partial result. Now the cursor is in row level which means the special Result will only 1167 * contains a row key. {@link Result#isCursor()} {@link Result#getCursor()} {@link Cursor} 1168 */ 1169 public Scan setNeedCursorResult(boolean needCursorResult) { 1170 this.needCursorResult = needCursorResult; 1171 return this; 1172 } 1173 1174 public boolean isNeedCursorResult() { 1175 return needCursorResult; 1176 } 1177 1178 /** 1179 * Create a new Scan with a cursor. It only set the position information like start row key. The 1180 * others (like cfs, stop row, limit) should still be filled in by the user. 1181 * {@link Result#isCursor()} {@link Result#getCursor()} {@link Cursor} 1182 */ 1183 public static Scan createScanFromCursor(Cursor cursor) { 1184 return new Scan().withStartRow(cursor.getRow()); 1185 } 1186}