Skip to content

Commit f87cce9

Browse files
author
karenx
committed
[GRPC] Optimize source conversion in gRPC search hits using zero-copy BytesRef
Signed-off-by: karenx <[email protected]>
1 parent bd914cb commit f87cce9

File tree

1 file changed

+17
-1
lines changed

1 file changed

+17
-1
lines changed

modules/transport-grpc/src/main/java/org/opensearch/transport/grpc/proto/response/search/SearchHitProtoUtils.java

Lines changed: 17 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,10 @@
88
package org.opensearch.transport.grpc.proto.response.search;
99

1010
import com.google.protobuf.ByteString;
11+
import com.google.protobuf.UnsafeByteOperations;
1112
import org.apache.lucene.search.Explanation;
13+
import org.apache.lucene.util.BytesRef;
14+
import org.opensearch.common.bytes.BytesArray;
1215
import org.opensearch.common.document.DocumentField;
1316
import org.opensearch.core.common.bytes.BytesReference;
1417
import org.opensearch.core.xcontent.ToXContent;
@@ -194,7 +197,20 @@ private static void processMetadataFields(SearchHit hit, org.opensearch.protobuf
194197
*/
195198
private static void processSource(SearchHit hit, org.opensearch.protobufs.Hit.Builder hitBuilder) {
196199
if (hit.getSourceRef() != null) {
197-
hitBuilder.setSource(ByteString.copyFrom(BytesReference.toBytes(hit.getSourceRef())));
200+
BytesReference sourceRef = hit.getSourceRef();
201+
BytesRef bytesRef = sourceRef.toBytesRef();
202+
203+
if (sourceRef instanceof BytesArray) {
204+
if (bytesRef.offset == 0 && bytesRef.length == bytesRef.bytes.length) {
205+
hitBuilder.setSource(UnsafeByteOperations.unsafeWrap(bytesRef.bytes));
206+
} else {
207+
hitBuilder.setSource(UnsafeByteOperations.unsafeWrap(
208+
bytesRef.bytes, bytesRef.offset, bytesRef.length));
209+
}
210+
} else {
211+
hitBuilder.setSource(ByteString.copyFrom(
212+
bytesRef.bytes, bytesRef.offset, bytesRef.length));
213+
}
198214
}
199215
}
200216

0 commit comments

Comments
 (0)