Skip to content

Instantly share code, notes, and snippets.

@chatman
Last active August 29, 2015 14:14
Show Gist options
  • Save chatman/4436881e9373760715fc to your computer and use it in GitHub Desktop.
Save chatman/4436881e9373760715fc to your computer and use it in GitHub Desktop.
CRUDHandler.java
package org.apache.solr.core;
import java.util.List;
import org.apache.solr.common.SolrException;
import org.apache.solr.common.params.ModifiableSolrParams;
import org.apache.solr.common.params.SolrParams;
import org.apache.solr.common.util.StrUtils;
import org.apache.solr.handler.UpdateRequestHandler;
import org.apache.solr.request.SolrQueryRequest;
import org.apache.solr.request.SolrRequestHandler;
import org.apache.solr.response.SolrQueryResponse;
public class CRUDHandler extends UpdateRequestHandler {
@Override
public void handleRequestBody(SolrQueryRequest req, SolrQueryResponse rsp) throws Exception {
SolrParams params = req.getOriginalParams();
ModifiableSolrParams mparams = new ModifiableSolrParams(params);
String httpMethod = (String) req.getContext().get("httpMethod");
String path = (String) req.getContext().get("path");
List<String> pieces = StrUtils.splitSmart(path, '/');
String id = (pieces.size()>=3)? pieces.get(2): null;
String action = (pieces.size()>=4)? pieces.get(3): null;
// to retrieve a document by id,
// example: http://localhost:8983/gettingstarted/crud/{id}
if("GET".equals(httpMethod) && action==null || "get".equalsIgnoreCase(action)) {
if(id==null)
throw new SolrException(SolrException.ErrorCode.BAD_REQUEST, "Missing id for a get request.");
mparams.add("q", "id:" + id);
mparams.add("wt", "json");
req.forward("/select", mparams, rsp);
}
// to delete a document by id,
// example: http://localhost:8983/gettingstarted/crud/{id}/delete
else if("GET".equals(httpMethod) && "delete".equalsIgnoreCase(action)) {
mparams.add("stream.body", "<delete><id>" + id + "</id></delete>");
mparams.add("commit", "true");
req.forward("/update", mparams, rsp);
}
// to add/update a document,
// example: POST '[{"id": "1", "title": "hello world document"}]' to
// http://localhost:8983/gettingstarted/crud
else if("POST".equals(httpMethod)) {
mparams.add("commit", "true");
req.setParams(mparams);
super.handleRequestBody(req, rsp);
}
}
@Override
public String getDescription() {
return "CRUD handler to provide a simple REST like interface to add, retrieve and delete documents.";
}
@Override
public SolrRequestHandler getSubHandler(String subPath) {
if(StrUtils.splitSmart(subPath, '/').size() > 4)
return null;
return this;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment