-
Notifications
You must be signed in to change notification settings - Fork 25.6k
Add recursive chunker #126866
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
dan-rubinstein
merged 13 commits into
elastic:main
from
dan-rubinstein:recursive-chunking-strategy
Jun 18, 2025
Merged
Add recursive chunker #126866
Changes from 10 commits
Commits
Show all changes
13 commits
Select commit
Hold shift + click to select a range
5167b21
Add recursive chunker
dan-rubinstein 7d9e07c
Update docs/changelog/126866.yaml
dan-rubinstein 8418223
Merge branch 'main' into recursive-chunking-strategy
dan-rubinstein 0685124
Clean up separator sets and add asMap function for RecrusiveChunkingS…
dan-rubinstein f40947a
Add javadoc for chunker, add tests, reduce word counting operations
dan-rubinstein 6f649fc
Merge branch 'main' into recursive-chunking-strategy
dan-rubinstein c8a5f0c
Remove split merging and add long document unit test
dan-rubinstein 6f337a8
Merge branch 'main' into recursive-chunking-strategy
dan-rubinstein 6035d76
[CI] Auto commit changes from spotless
29498f7
Add markdown chunking tests and reduce substring calls
dan-rubinstein 0d6b461
Clean up matcher logic
dan-rubinstein 3edf75e
Add testing for not splitting after valid chunk is found
dan-rubinstein 3ac8b94
Merge branch 'main' into recursive-chunking-strategy
elasticmachine File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,5 @@ | ||
| pr: 126866 | ||
| summary: Add recursive chunker | ||
| area: Machine Learning | ||
| type: enhancement | ||
| issues: [] |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
31 changes: 31 additions & 0 deletions
31
...ugin/inference/src/main/java/org/elasticsearch/xpack/inference/chunking/ChunkerUtils.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,31 @@ | ||
| /* | ||
| * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one | ||
| * or more contributor license agreements. Licensed under the Elastic License | ||
| * 2.0; you may not use this file except in compliance with the Elastic License | ||
| * 2.0. | ||
| */ | ||
|
|
||
| package org.elasticsearch.xpack.inference.chunking; | ||
|
|
||
| import com.ibm.icu.text.BreakIterator; | ||
|
|
||
| public class ChunkerUtils { | ||
|
|
||
| // setText() should be applied before using this function. | ||
| static int countWords(int start, int end, BreakIterator wordIterator) { | ||
| assert start < end; | ||
| wordIterator.preceding(start); // start of the current word | ||
|
|
||
| int boundary = wordIterator.current(); | ||
| int wordCount = 0; | ||
| while (boundary != BreakIterator.DONE && boundary <= end) { | ||
| int wordStatus = wordIterator.getRuleStatus(); | ||
| if (wordStatus != BreakIterator.WORD_NONE) { | ||
| wordCount++; | ||
| } | ||
| boundary = wordIterator.next(); | ||
| } | ||
|
|
||
| return wordCount; | ||
| } | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
125 changes: 125 additions & 0 deletions
125
.../inference/src/main/java/org/elasticsearch/xpack/inference/chunking/RecursiveChunker.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,125 @@ | ||
| /* | ||
| * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one | ||
| * or more contributor license agreements. Licensed under the Elastic License | ||
| * 2.0; you may not use this file except in compliance with the Elastic License | ||
| * 2.0. | ||
| */ | ||
|
|
||
| package org.elasticsearch.xpack.inference.chunking; | ||
|
|
||
| import com.ibm.icu.text.BreakIterator; | ||
|
|
||
| import org.elasticsearch.common.Strings; | ||
| import org.elasticsearch.inference.ChunkingSettings; | ||
|
|
||
| import java.util.ArrayList; | ||
| import java.util.List; | ||
| import java.util.regex.Pattern; | ||
|
|
||
| /** | ||
| * Split text into chunks recursively based on a list of separator regex strings. | ||
| * The maximum chunk size is measured in words and controlled | ||
| * by {@code maxNumberWordsPerChunk}. For each separator the chunker will go through the following process: | ||
| * 1. Split the text on each regex match of the separator. | ||
| * 2. For each chunk after the merge: | ||
| * 1. Return it if it is within the maximum chunk size. | ||
| * 2. Repeat the process using the next separator in the list if the chunk exceeds the maximum chunk size. | ||
| * If there are no more separators left to try, run the {@code SentenceBoundaryChunker} with the provided | ||
| * max chunk size and no overlaps. | ||
| */ | ||
| public class RecursiveChunker implements Chunker { | ||
| private final BreakIterator wordIterator; | ||
|
|
||
| public RecursiveChunker() { | ||
| wordIterator = BreakIterator.getWordInstance(); | ||
| } | ||
|
|
||
| @Override | ||
| public List<ChunkOffset> chunk(String input, ChunkingSettings chunkingSettings) { | ||
| if (chunkingSettings instanceof RecursiveChunkingSettings recursiveChunkingSettings) { | ||
| return chunk( | ||
| input, | ||
| new ChunkOffset(0, input.length()), | ||
| recursiveChunkingSettings.getSeparators(), | ||
| recursiveChunkingSettings.getMaxChunkSize(), | ||
| 0 | ||
| ); | ||
| } else { | ||
| throw new IllegalArgumentException( | ||
| Strings.format("RecursiveChunker can't use ChunkingSettings with strategy [%s]", chunkingSettings.getChunkingStrategy()) | ||
| ); | ||
| } | ||
| } | ||
|
|
||
| private List<ChunkOffset> chunk(String input, ChunkOffset offset, List<String> separators, int maxChunkSize, int separatorIndex) { | ||
| if (offset.start() == offset.end() || isChunkWithinMaxSize(buildChunkOffsetAndCount(input, offset), maxChunkSize)) { | ||
| return List.of(offset); | ||
| } | ||
|
|
||
| if (separatorIndex > separators.size() - 1) { | ||
| return chunkWithBackupChunker(input, offset, maxChunkSize); | ||
| } | ||
|
|
||
| var potentialChunks = splitTextBySeparatorRegex(input, offset, separators.get(separatorIndex)); | ||
| var actualChunks = new ArrayList<ChunkOffset>(); | ||
| for (var potentialChunk : potentialChunks) { | ||
| if (isChunkWithinMaxSize(potentialChunk, maxChunkSize)) { | ||
| actualChunks.add(potentialChunk.chunkOffset()); | ||
| } else { | ||
| actualChunks.addAll(chunk(input, potentialChunk.chunkOffset(), separators, maxChunkSize, separatorIndex + 1)); | ||
| } | ||
| } | ||
|
|
||
| return actualChunks; | ||
| } | ||
|
|
||
| private boolean isChunkWithinMaxSize(ChunkOffsetAndCount chunkOffsetAndCount, int maxChunkSize) { | ||
| return chunkOffsetAndCount.wordCount <= maxChunkSize; | ||
| } | ||
|
|
||
| private ChunkOffsetAndCount buildChunkOffsetAndCount(String fullText, ChunkOffset offset) { | ||
| wordIterator.setText(fullText); | ||
| return new ChunkOffsetAndCount(offset, ChunkerUtils.countWords(offset.start(), offset.end(), wordIterator)); | ||
| } | ||
|
|
||
| private List<ChunkOffsetAndCount> splitTextBySeparatorRegex(String input, ChunkOffset offset, String separatorRegex) { | ||
| var pattern = Pattern.compile(separatorRegex, Pattern.MULTILINE); | ||
dan-rubinstein marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| var matcher = pattern.matcher(input); | ||
|
|
||
| var chunkOffsets = new ArrayList<ChunkOffsetAndCount>(); | ||
| int chunkStart = offset.start(); | ||
| int searchStart = offset.start(); | ||
| while (matcher.find(searchStart)) { | ||
davidkyle marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
| var chunkEnd = matcher.start(); | ||
| if (chunkEnd >= offset.end()) { | ||
dan-rubinstein marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
| break; // No more matches within the chunk offset | ||
| } | ||
|
|
||
| if (chunkStart < chunkEnd) { | ||
| chunkOffsets.add(buildChunkOffsetAndCount(input, new ChunkOffset(chunkStart, chunkEnd))); | ||
| } | ||
| chunkStart = chunkEnd; | ||
| searchStart = matcher.end(); | ||
| } | ||
|
|
||
| if (chunkStart < offset.end()) { | ||
| chunkOffsets.add(buildChunkOffsetAndCount(input, new ChunkOffset(chunkStart, offset.end()))); | ||
| } | ||
|
|
||
| return chunkOffsets; | ||
| } | ||
|
|
||
| private List<ChunkOffset> chunkWithBackupChunker(String input, ChunkOffset offset, int maxChunkSize) { | ||
| var chunks = new SentenceBoundaryChunker().chunk( | ||
| input.substring(offset.start(), offset.end()), | ||
| new SentenceBoundaryChunkingSettings(maxChunkSize, 0) | ||
| ); | ||
| var chunksWithOffsets = new ArrayList<ChunkOffset>(); | ||
| for (var chunk : chunks) { | ||
| chunksWithOffsets.add(new ChunkOffset(chunk.start() + offset.start(), chunk.end() + offset.start())); | ||
| } | ||
| return chunksWithOffsets; | ||
| } | ||
|
|
||
| private record ChunkOffsetAndCount(ChunkOffset chunkOffset, int wordCount) {} | ||
| } | ||
173 changes: 173 additions & 0 deletions
173
...e/src/main/java/org/elasticsearch/xpack/inference/chunking/RecursiveChunkingSettings.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,173 @@ | ||
| /* | ||
| * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one | ||
| * or more contributor license agreements. Licensed under the Elastic License | ||
| * 2.0; you may not use this file except in compliance with the Elastic License | ||
| * 2.0. | ||
| */ | ||
|
|
||
| package org.elasticsearch.xpack.inference.chunking; | ||
|
|
||
| import org.elasticsearch.TransportVersion; | ||
| import org.elasticsearch.common.Strings; | ||
| import org.elasticsearch.common.ValidationException; | ||
| import org.elasticsearch.common.io.stream.StreamInput; | ||
| import org.elasticsearch.common.io.stream.StreamOutput; | ||
| import org.elasticsearch.inference.ChunkingSettings; | ||
| import org.elasticsearch.inference.ChunkingStrategy; | ||
| import org.elasticsearch.inference.ModelConfigurations; | ||
| import org.elasticsearch.xcontent.XContentBuilder; | ||
| import org.elasticsearch.xpack.inference.services.ServiceUtils; | ||
|
|
||
| import java.io.IOException; | ||
| import java.util.Arrays; | ||
| import java.util.EnumSet; | ||
| import java.util.List; | ||
| import java.util.Locale; | ||
| import java.util.Map; | ||
| import java.util.Objects; | ||
| import java.util.Set; | ||
|
|
||
| public class RecursiveChunkingSettings implements ChunkingSettings { | ||
| public static final String NAME = "RecursiveChunkingSettings"; | ||
| private static final ChunkingStrategy STRATEGY = ChunkingStrategy.RECURSIVE; | ||
| private static final int MAX_CHUNK_SIZE_LOWER_LIMIT = 10; | ||
| private static final int MAX_CHUNK_SIZE_UPPER_LIMIT = 300; | ||
|
|
||
| private static final Set<String> VALID_KEYS = Set.of( | ||
| ChunkingSettingsOptions.STRATEGY.toString(), | ||
| ChunkingSettingsOptions.MAX_CHUNK_SIZE.toString(), | ||
| ChunkingSettingsOptions.SEPARATOR_SET.toString(), | ||
| ChunkingSettingsOptions.SEPARATORS.toString() | ||
| ); | ||
|
|
||
| private final int maxChunkSize; | ||
| private final List<String> separators; | ||
|
|
||
| public RecursiveChunkingSettings(int maxChunkSize, List<String> separators) { | ||
| this.maxChunkSize = maxChunkSize; | ||
| this.separators = separators == null ? SeparatorSet.PLAINTEXT.getSeparators() : separators; | ||
| } | ||
|
|
||
| public RecursiveChunkingSettings(StreamInput in) throws IOException { | ||
| maxChunkSize = in.readInt(); | ||
| separators = in.readCollectionAsList(StreamInput::readString); | ||
| } | ||
|
|
||
| public static RecursiveChunkingSettings fromMap(Map<String, Object> map) { | ||
| ValidationException validationException = new ValidationException(); | ||
|
|
||
| var invalidSettings = map.keySet().stream().filter(key -> VALID_KEYS.contains(key) == false).toArray(); | ||
| if (invalidSettings.length > 0) { | ||
| validationException.addValidationError( | ||
| Strings.format("Recursive chunking settings can not have the following settings: %s", Arrays.toString(invalidSettings)) | ||
| ); | ||
| } | ||
|
|
||
| Integer maxChunkSize = ServiceUtils.extractRequiredPositiveIntegerBetween( | ||
| map, | ||
| ChunkingSettingsOptions.MAX_CHUNK_SIZE.toString(), | ||
| MAX_CHUNK_SIZE_LOWER_LIMIT, | ||
| MAX_CHUNK_SIZE_UPPER_LIMIT, | ||
| ModelConfigurations.CHUNKING_SETTINGS, | ||
| validationException | ||
| ); | ||
|
|
||
| SeparatorSet separatorSet = ServiceUtils.extractOptionalEnum( | ||
| map, | ||
| ChunkingSettingsOptions.SEPARATOR_SET.toString(), | ||
| ModelConfigurations.CHUNKING_SETTINGS, | ||
| SeparatorSet::fromString, | ||
| EnumSet.allOf(SeparatorSet.class), | ||
| validationException | ||
| ); | ||
|
|
||
| List<String> separators = ServiceUtils.extractOptionalList( | ||
| map, | ||
| ChunkingSettingsOptions.SEPARATORS.toString(), | ||
| String.class, | ||
| validationException | ||
| ); | ||
|
|
||
| if (separators != null && separatorSet != null) { | ||
| validationException.addValidationError("Recursive chunking settings can not have both separators and separator_set"); | ||
| } | ||
|
|
||
| if (separatorSet != null) { | ||
| separators = separatorSet.getSeparators(); | ||
| } else if (separators != null && separators.isEmpty()) { | ||
| validationException.addValidationError("Recursive chunking settings can not have an empty list of separators"); | ||
| } | ||
|
|
||
| if (validationException.validationErrors().isEmpty() == false) { | ||
| throw validationException; | ||
| } | ||
|
|
||
| return new RecursiveChunkingSettings(maxChunkSize, separators); | ||
| } | ||
|
|
||
| public int getMaxChunkSize() { | ||
| return maxChunkSize; | ||
| } | ||
|
|
||
| public List<String> getSeparators() { | ||
| return separators; | ||
| } | ||
|
|
||
| @Override | ||
| public ChunkingStrategy getChunkingStrategy() { | ||
| return STRATEGY; | ||
| } | ||
|
|
||
| @Override | ||
| public Map<String, Object> asMap() { | ||
| return Map.of( | ||
| ChunkingSettingsOptions.STRATEGY.toString(), | ||
| STRATEGY.toString().toLowerCase(Locale.ROOT), | ||
| ChunkingSettingsOptions.MAX_CHUNK_SIZE.toString(), | ||
| maxChunkSize, | ||
| ChunkingSettingsOptions.SEPARATORS.toString(), | ||
| separators | ||
| ); | ||
| } | ||
|
|
||
| @Override | ||
| public String getWriteableName() { | ||
| return NAME; | ||
| } | ||
|
|
||
| @Override | ||
| public TransportVersion getMinimalSupportedVersion() { | ||
| return null; // TODO: Add transport version | ||
| } | ||
|
|
||
| @Override | ||
| public void writeTo(StreamOutput out) throws IOException { | ||
| out.writeInt(maxChunkSize); | ||
| out.writeCollection(separators, StreamOutput::writeString); | ||
| } | ||
|
|
||
| @Override | ||
| public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException { | ||
| builder.startObject(); | ||
| { | ||
| builder.field(ChunkingSettingsOptions.STRATEGY.toString(), STRATEGY); | ||
| builder.field(ChunkingSettingsOptions.MAX_CHUNK_SIZE.toString(), maxChunkSize); | ||
| builder.field(ChunkingSettingsOptions.SEPARATORS.toString(), separators); | ||
| } | ||
| builder.endObject(); | ||
| return builder; | ||
| } | ||
|
|
||
| @Override | ||
| public boolean equals(Object o) { | ||
| if (this == o) return true; | ||
| if (o == null || getClass() != o.getClass()) return false; | ||
| RecursiveChunkingSettings that = (RecursiveChunkingSettings) o; | ||
| return Objects.equals(maxChunkSize, that.maxChunkSize) && Objects.equals(separators, that.separators); | ||
| } | ||
|
|
||
| @Override | ||
| public int hashCode() { | ||
| return Objects.hash(maxChunkSize, separators); | ||
| } | ||
| } |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.