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