Skip to content

Apache Lucene open-source search software

SOLR-2112 -- add a streaming interface to solrj api. Implemented with BinaryResponseParser callbacks

Ryan McKinley629e03811fd5
diff --git a/solr/CHANGES.txt b/solr/CHANGES.txt
index 15e8c940146..814a85fda2a 100644
--- a/solr/CHANGES.txt
+++ b/solr/CHANGES.txt
@@ -263,6 +263,8 @@ New Features
no documents if the query parser returns null. This also prevents an
exception from being thrown by the default parser if "q" is missing. (yonik)
+* SOLR-2112: Solrj API now supports streaming results. (ryan)
+
Optimizations
----------------------
diff --git a/solr/src/common/org/apache/solr/common/util/JavaBinCodec.java b/solr/src/common/org/apache/solr/common/util/JavaBinCodec.java
index 08f776b28b4..cb7836c1906 100755
--- a/solr/src/common/org/apache/solr/common/util/JavaBinCodec.java
+++ b/solr/src/common/org/apache/solr/common/util/JavaBinCodec.java
@@ -151,7 +151,7 @@ public class JavaBinCodec {
protected static final Object END_OBJ = new Object();
- byte tagByte;
+ protected byte tagByte;
public Object readVal(FastInputStream dis) throws IOException {
tagByte = dis.readByte();
diff --git a/solr/src/java/org/apache/solr/response/BinaryResponseWriter.java b/solr/src/java/org/apache/solr/response/BinaryResponseWriter.java
index ea7f662cab7..76e018c041c 100755
--- a/solr/src/java/org/apache/solr/response/BinaryResponseWriter.java
+++ b/solr/src/java/org/apache/solr/response/BinaryResponseWriter.java
@@ -58,12 +58,12 @@ public class BinaryResponseWriter implements BinaryQueryResponseWriter {
/* NOOP */
}
- private static class Resolver implements JavaBinCodec.ObjectResolver {
- private final SolrQueryRequest solrQueryRequest;
- private IndexSchema schema;
- private SolrIndexSearcher searcher;
- private final Set<String> returnFields;
- private final boolean includeScore;
+ public static class Resolver implements JavaBinCodec.ObjectResolver {
+ protected final SolrQueryRequest solrQueryRequest;
+ protected IndexSchema schema;
+ protected SolrIndexSearcher searcher;
+ protected final Set<String> returnFields;
+ protected final boolean includeScore;
// transmit field values using FieldType.toObject()
// rather than the String from FieldType.toExternal()
diff --git a/solr/src/solrj/org/apache/solr/client/solrj/SolrRequest.java b/solr/src/solrj/org/apache/solr/client/solrj/SolrRequest.java
index 57833fe8018..e60df31a48b 100644
--- a/solr/src/solrj/org/apache/solr/client/solrj/SolrRequest.java
+++ b/solr/src/solrj/org/apache/solr/client/solrj/SolrRequest.java
@@ -40,6 +40,8 @@ public abstract class SolrRequest implements Serializable
private String path = null;
private ResponseParser responseParser;
+ private StreamingResponseCallback callback;
+
//---------------------------------------------------------
//---------------------------------------------------------
@@ -83,6 +85,14 @@ public abstract class SolrRequest implements Serializable
this.responseParser = responseParser;
}
+ public StreamingResponseCallback getStreamingResponseCallback() {
+ return callback;
+ }
+
+ public void setStreamingResponseCallback(StreamingResponseCallback callback) {
+ this.callback = callback;
+ }
+
public abstract SolrParams getParams();
public abstract Collection<ContentStream> getContentStreams() throws IOException;
public abstract SolrResponse process( SolrServer server ) throws SolrServerException, IOException;
diff --git a/solr/src/solrj/org/apache/solr/client/solrj/SolrServer.java b/solr/src/solrj/org/apache/solr/client/solrj/SolrServer.java
index ab05e6712b5..72c6160af68 100644
--- a/solr/src/solrj/org/apache/solr/client/solrj/SolrServer.java
+++ b/solr/src/solrj/org/apache/solr/client/solrj/SolrServer.java
@@ -31,6 +31,7 @@ import org.apache.solr.client.solrj.response.SolrPingResponse;
import org.apache.solr.client.solrj.response.UpdateResponse;
import org.apache.solr.client.solrj.SolrRequest.METHOD;
import org.apache.solr.client.solrj.beans.DocumentObjectBinder;
+import org.apache.solr.client.solrj.impl.StreamingBinaryResponseParser;
import org.apache.solr.common.SolrInputDocument;
import org.apache.solr.common.params.SolrParams;
import org.apache.solr.common.util.NamedList;
@@ -121,7 +122,27 @@ public abstract class SolrServer implements Serializable
public QueryResponse query(SolrParams params, METHOD method) throws SolrServerException {
return new QueryRequest( params, method ).process( this );
}
-
+
+ /**
+ * Query solr, and stream the results. Unlike the standard query, this will
+ * send events for each Document rather then add them to the QueryResponse.
+ *
+ * Although this function returns a 'QueryResponse' it should be used with care
+ * since it excludes anything that was passed to callback. Also note that
+ * future version may pass even more info to the callback and may not return
+ * the results in the QueryResponse.
+ *
+ * @since solr 4.0
+ */
+ public QueryResponse queryAndStreamResponse( SolrParams params, StreamingResponseCallback callback ) throws SolrServerException, IOException
+ {
+ ResponseParser parser = new StreamingBinaryResponseParser( callback );
+ QueryRequest req = new QueryRequest( params );
+ req.setStreamingResponseCallback( callback );
+ req.setResponseParser( parser );
+ return req.process(this);
+ }
+
/**
* SolrServer implementations need to implement how a request is actually processed
*/
diff --git a/solr/src/solrj/org/apache/solr/client/solrj/StreamingResponseCallback.java b/solr/src/solrj/org/apache/solr/client/solrj/StreamingResponseCallback.java
new file mode 100644
index 00000000000..24973fc451c
--- /dev/null
+++ b/solr/src/solrj/org/apache/solr/client/solrj/StreamingResponseCallback.java
@@ -0,0 +1,37 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.solr.client.solrj;
+
+import org.apache.solr.common.SolrDocument;
+
+/**
+ * A callback interface for streaming response
+ *
+ * @since solr 4.0
+ */
+public abstract class StreamingResponseCallback {
+ /*
+ * Called for each SolrDocument in the response
+ */
+ public abstract void streamSolrDocument( SolrDocument doc );
+
+ /*
+ * Called at the beginning of each DocList (and SolrDocumentList)
+ */
+ public abstract void streamDocListInfo( long numFound, long start, Float maxScore );
+}
diff --git a/solr/src/solrj/org/apache/solr/client/solrj/impl/StreamingBinaryResponseParser.java b/solr/src/solrj/org/apache/solr/client/solrj/impl/StreamingBinaryResponseParser.java
new file mode 100644
index 00000000000..db87f126751
--- /dev/null
+++ b/solr/src/solrj/org/apache/solr/client/solrj/impl/StreamingBinaryResponseParser.java
@@ -0,0 +1,89 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.solr.client.solrj.impl;
+
+import org.apache.solr.client.solrj.StreamingResponseCallback;
+import org.apache.solr.common.SolrDocument;
+import org.apache.solr.common.SolrDocumentList;
+import org.apache.solr.common.SolrException;
+import org.apache.solr.common.util.FastInputStream;
+import org.apache.solr.common.util.NamedList;
+import org.apache.solr.common.util.JavaBinCodec;
+
+import java.io.IOException;
+import java.io.InputStream;
+import java.util.List;
+
+/**
+ * A BinaryResponseParser that sends callback events rather then build
+ * a large response
+ *
+ * @version $Id: StreamingBinaryResponseParser.java 990180 2010-08-27 15:40:17Z rmuir $
+ * @since solr 4.0
+ */
+public class StreamingBinaryResponseParser extends BinaryResponseParser {
+ final StreamingResponseCallback callback;
+
+ public StreamingBinaryResponseParser( StreamingResponseCallback cb )
+ {
+ this.callback = cb;
+ }
+
+ @Override
+ public NamedList<Object> processResponse(InputStream body, String encoding) {
+ try {
+ JavaBinCodec codec = new JavaBinCodec() {
+
+ public SolrDocument readSolrDocument(FastInputStream dis) throws IOException {
+ SolrDocument doc = super.readSolrDocument(dis);
+ callback.streamSolrDocument( doc );
+ return null;
+ }
+
+ public SolrDocumentList readSolrDocumentList(FastInputStream dis) throws IOException {
+ SolrDocumentList solrDocs = new SolrDocumentList();
+ List list = (List) readVal(dis);
+ solrDocs.setNumFound((Long) list.get(0));
+ solrDocs.setStart((Long) list.get(1));
+ solrDocs.setMaxScore((Float) list.get(2));
+
+ callback.streamDocListInfo(
+ solrDocs.getNumFound(),
+ solrDocs.getStart(),
+ solrDocs.getMaxScore() );
+
+ // Read the Array
+ tagByte = dis.readByte();
+ if( (tagByte >>> 5) != (ARR >>> 5) ) {
+ throw new RuntimeException( "doclist must have an array" );
+ }
+ int sz = readSize(dis);
+ for (int i = 0; i < sz; i++) {
+ // must be a SolrDocument
+ readVal( dis );
+ }
+ return solrDocs;
+ }
+ };
+
+ return (NamedList<Object>) codec.unmarshal(body);
+ }
+ catch (IOException e) {
+ throw new SolrException(SolrException.ErrorCode.SERVER_ERROR, "parsing error", e);
+ }
+ }
+}
diff --git a/solr/src/test/org/apache/solr/client/solrj/SolrExampleTests.java b/solr/src/test/org/apache/solr/client/solrj/SolrExampleTests.java
index 88907f9f993..3f177359cf1 100644
--- a/solr/src/test/org/apache/solr/client/solrj/SolrExampleTests.java
+++ b/solr/src/test/org/apache/solr/client/solrj/SolrExampleTests.java
@@ -24,21 +24,26 @@ import java.io.File;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
+import java.util.concurrent.atomic.AtomicInteger;
import junit.framework.Assert;
+import org.apache.solr.client.solrj.impl.CommonsHttpSolrServer;
import org.apache.solr.client.solrj.request.DirectXmlRequest;
import org.apache.solr.client.solrj.request.LukeRequest;
+import org.apache.solr.client.solrj.request.RequestWriter;
import org.apache.solr.client.solrj.request.SolrPing;
import org.apache.solr.client.solrj.response.FieldStatsInfo;
import org.apache.solr.client.solrj.request.UpdateRequest;
import org.apache.solr.client.solrj.request.ContentStreamUpdateRequest;
import org.apache.solr.client.solrj.request.AbstractUpdateRequest;
+import org.apache.solr.client.solrj.request.AbstractUpdateRequest.ACTION;
import org.apache.solr.client.solrj.response.LukeResponse;
import org.apache.solr.client.solrj.response.QueryResponse;
import org.apache.solr.client.solrj.response.FacetField;
import org.apache.solr.client.solrj.response.UpdateResponse;
import org.apache.solr.client.solrj.util.ClientUtils;
+import org.apache.solr.common.SolrDocument;
import org.apache.solr.common.SolrInputDocument;
import org.apache.solr.common.util.XML;
import org.apache.solr.common.util.NamedList;
@@ -562,4 +567,47 @@ abstract public class SolrExampleTests extends SolrJettyTestBase
// System.out.println( rsp.getResults().getNumFound() + " :::: 444: "+ff.getValues() );
}
+
+
+ @Test
+ public void testStreamingRequest() throws Exception {
+ // Empty the database...
+ server.deleteByQuery( "*:*" );// delete everything!
+ server.commit();
+ assertNumFound( "*:*", 0 ); // make sure it got in
+
+ // Add some docs to the index
+ UpdateRequest req = new UpdateRequest();
+ for( int i=0; i<10; i++ ) {
+ SolrInputDocument doc = new SolrInputDocument();
+ doc.addField("id", "" + i );
+ doc.addField("cat", "foocat");
+ req.add( doc );
+ }
+ req.setAction(ACTION.COMMIT, true, true );
+ req.process( server );
+
+ // Make sure it ran OK
+ SolrQuery query = new SolrQuery("*:*");
+ QueryResponse response = server.query(query);
+ assertEquals(0, response.getStatus());
+ assertEquals(10, response.getResults().getNumFound());
+
+ // Now make sure each document gets output
+ final AtomicInteger cnt = new AtomicInteger( 0 );
+ server.queryAndStreamResponse(query, new StreamingResponseCallback() {
+
+ @Override
+ public void streamDocListInfo(long numFound, long start, Float maxScore) {
+ assertEquals(10, numFound );
+ }
+
+ @Override
+ public void streamSolrDocument(SolrDocument doc) {
+ cnt.incrementAndGet();
+ }
+
+ });
+ assertEquals(10, cnt.get() );
+ }
}
diff --git a/solr/src/webapp/src/org/apache/solr/client/solrj/embedded/EmbeddedSolrServer.java b/solr/src/webapp/src/org/apache/solr/client/solrj/embedded/EmbeddedSolrServer.java
index eb5adf2c808..e0cd8714919 100644
--- a/solr/src/webapp/src/org/apache/solr/client/solrj/embedded/EmbeddedSolrServer.java
+++ b/solr/src/webapp/src/org/apache/solr/client/solrj/embedded/EmbeddedSolrServer.java
@@ -17,15 +17,24 @@
package org.apache.solr.client.solrj.embedded;
+import java.io.ByteArrayInputStream;
+import java.io.ByteArrayOutputStream;
import java.io.IOException;
+import java.io.InputStream;
+import java.util.Set;
+import org.apache.lucene.document.Document;
import org.apache.solr.client.solrj.SolrRequest;
import org.apache.solr.client.solrj.SolrServer;
import org.apache.solr.client.solrj.SolrServerException;
+import org.apache.solr.client.solrj.StreamingResponseCallback;
+import org.apache.solr.common.SolrDocument;
+import org.apache.solr.common.SolrDocumentList;
import org.apache.solr.common.SolrException;
import org.apache.solr.common.params.CommonParams;
import org.apache.solr.common.params.ModifiableSolrParams;
import org.apache.solr.common.params.SolrParams;
+import org.apache.solr.common.util.JavaBinCodec;
import org.apache.solr.common.util.NamedList;
import org.apache.solr.core.CoreContainer;
import org.apache.solr.core.CoreDescriptor;
@@ -34,6 +43,8 @@ import org.apache.solr.request.SolrQueryRequest;
import org.apache.solr.request.SolrRequestHandler;
import org.apache.solr.response.BinaryResponseWriter;
import org.apache.solr.response.SolrQueryResponse;
+import org.apache.solr.search.DocIterator;
+import org.apache.solr.search.DocList;
import org.apache.solr.servlet.SolrRequestParsers;
/**
@@ -141,6 +152,75 @@ public class EmbeddedSolrServer extends SolrServer
throw new SolrServerException( rsp.getException() );
}
+ // Check if this should stream results
+ if( request.getStreamingResponseCallback() != null ) {
+ try {
+ final StreamingResponseCallback callback = request.getStreamingResponseCallback();
+ BinaryResponseWriter.Resolver resolver =
+ new BinaryResponseWriter.Resolver( req, rsp.getReturnFields())
+ {
+ @Override
+ public void writeDocList(DocList ids, JavaBinCodec codec) throws IOException {
+ // write an empty list...
+ SolrDocumentList docs = new SolrDocumentList();
+ docs.setNumFound( ids.matches() );
+ docs.setStart( ids.offset() );
+ docs.setMaxScore( ids.maxScore() );
+ codec.writeSolrDocumentList( docs );
+
+ int sz = ids.size();
+
+ if(searcher == null) searcher = solrQueryRequest.getSearcher();
+ if(schema == null) schema = solrQueryRequest.getSchema();
+ DocIterator iterator = ids.iterator();
+ for (int i = 0; i < sz; i++) {
+ int id = iterator.nextDoc();
+ Document doc = searcher.doc(id, returnFields);
+ SolrDocument sdoc = getDoc(doc);
+ if (includeScore && ids.hasScores()) {
+ sdoc.addField("score", iterator.score());
+ }
+ callback.streamSolrDocument( sdoc );
+ }
+ }
+ };
+
+
+ ByteArrayOutputStream out = new ByteArrayOutputStream();
+ new JavaBinCodec(resolver) {
+
+ @Override
+ public void writeSolrDocument(SolrDocument doc, Set<String> fields) throws IOException {
+ callback.streamSolrDocument( doc );
+ //super.writeSolrDocument( doc, fields );
+ }
+
+ @Override
+ public void writeSolrDocumentList(SolrDocumentList docs) throws IOException {
+ if( docs.size() > 0 ) {
+ SolrDocumentList tmp = new SolrDocumentList();
+ tmp.setMaxScore( docs.getMaxScore() );
+ tmp.setNumFound( docs.getNumFound() );
+ tmp.setStart( docs.getStart() );
+ docs = tmp;
+ }
+ callback.streamDocListInfo( docs.getNumFound(), docs.getStart(), docs.getMaxScore() );
+ super.writeSolrDocumentList(docs);
+ }
+
+ }.marshal(rsp.getValues(), out);
+
+ InputStream in = new ByteArrayInputStream(out.toByteArray());
+ return (NamedList<Object>) new JavaBinCodec(resolver).unmarshal(in);
+ }
+ catch (Exception ex) {
+ throw new RuntimeException(ex);
+ }
+ finally {
+ req.close();
+ }
+ }
+
// Now write it out
NamedList<Object> normalized = getParsedResponse(req, rsp);
req.close();