Apache Lucene open-source search software
SOLR-139 SOLR-3178 : Updateable documents, optimistic locking
Yonik Seeleye35df0b58f39
diff --git a/solr/CHANGES.txt b/solr/CHANGES.txtindex d74fa52c197..26663dd4e34 100644--- a/solr/CHANGES.txt+++ b/solr/CHANGES.txt@@ -291,6 +291,17 @@ New FeaturesParsing and simple error checking for the Version is now done insidethe code that creates the Analysis Factories. (Chris Male)+* SOLR-3178: Optimistic locking. If a _version_ is provided with an update+ that does not match the version in the index, an HTTP 409 error (Conflict)+ will result. (Per Steffensen, yonik)++* SOLR-139: Updateable documents. JSON Example:+ {"id":"mydoc", "f1":{"set":10}, "f2":{"add":20}} will result in field "f1"+ being set to 10, "f2" having an additional value of 20 added, and all+ other existing fields unchanged. All source fields must be stored for+ this feature to work correctly. (Ryan McKinley, Erik Hatcher, yonik)++Optimizations----------------------diff --git a/solr/core/src/java/org/apache/solr/handler/JsonLoader.java b/solr/core/src/java/org/apache/solr/handler/JsonLoader.javaindex c79eda1e5a3..20beb9dc51e 100644--- a/solr/core/src/java/org/apache/solr/handler/JsonLoader.java+++ b/solr/core/src/java/org/apache/solr/handler/JsonLoader.java@@ -19,9 +19,7 @@ package org.apache.solr.handler;import java.io.IOException;import java.io.Reader;import java.io.StringReader;-import java.util.Iterator;-import java.util.Map;-import java.util.Stack;+import java.util.*;import org.apache.commons.io.IOUtils;import org.apache.noggit.JSONParser;@@ -320,153 +318,142 @@ class JsonLoader extends ContentStreamLoader {+" at ["+parser.getPosition()+"]" );}}-- SolrInputDocument parseDoc(int ev) throws IOException- {- Stack<Object> stack = new Stack<Object>();- Object obj = null;- boolean inArray = false;- if( ev != JSONParser.OBJECT_START ) {- throw new SolrException(SolrException.ErrorCode.BAD_REQUEST, "object should already be started" );++ private SolrInputDocument parseDoc(int ev) throws IOException {+ assert ev == JSONParser.OBJECT_START;++ SolrInputDocument sdoc = new SolrInputDocument();+ for (;;) {+ SolrInputField sif = parseField();+ if (sif == null) return sdoc;+ SolrInputField prev = sdoc.put(sif.getName(), sif);+ if (prev != null) {+ // blech - repeated keys+ sif.addValue(prev.getValue(), prev.getBoost());+ }}-- while( true ) {- //System.out.println( ev + "["+JSONParser.getEventString(ev)+"] "+parser.wasKey() ); //+ parser.getString() );+ }- switch (ev) {- case JSONParser.STRING:- if( parser.wasKey() ) {- obj = stack.peek();- String v = parser.getString();- if( obj instanceof SolrInputField ) {- SolrInputField field = (SolrInputField)obj;- if( "boost".equals( v ) ) {- ev = parser.nextEvent();- if( ev != JSONParser.NUMBER &&- ev != JSONParser.LONG &&- ev != JSONParser.BIGNUMBER ) {- throw new SolrException(SolrException.ErrorCode.BAD_REQUEST, "boost should have number! "+JSONParser.getEventString(ev) );- }- field.setBoost((float)parser.getDouble());- }- else if( "value".equals( v ) ) {- // nothing special...- stack.push( field ); // so it can be popped- }- else {- throw new SolrException(SolrException.ErrorCode.BAD_REQUEST, "invalid key: "+v + " ["+ parser.getPosition()+"]" );- }- }- else if( obj instanceof SolrInputDocument ) {- SolrInputDocument doc = (SolrInputDocument)obj;- SolrInputField f = doc.get( v );- if( f == null ) {- f = new SolrInputField( v );- doc.put( f.getName(), f );- }- stack.push( f );- }- else {- throw new SolrException(SolrException.ErrorCode.BAD_REQUEST, "hymmm ["+ parser.getPosition()+"]" );- }- }- else {- addValToField(stack, parser.getString(), inArray, parser);- }- break;+ private SolrInputField parseField() throws IOException {+ int ev = parser.nextEvent();+ if (ev == JSONParser.OBJECT_END) {+ return null;+ }- case JSONParser.LONG:- case JSONParser.NUMBER:- case JSONParser.BIGNUMBER:- addValToField(stack, parser.getNumberChars().toString(), inArray, parser);- break;-- case JSONParser.BOOLEAN:- addValToField(stack, parser.getBoolean(),inArray, parser);- break;+ String fieldName = parser.getString();+ SolrInputField sif = new SolrInputField(fieldName);+ parseFieldValue(sif);+ return sif;+ }- case JSONParser.NULL:- parser.getNull();- /*** if we wanted to remove the field from the document now...- if (!inArray) {- Object o = stack.peek();- // if null was only value in the field, then remove the field- if (o instanceof SolrInputField) {- SolrInputField sif = (SolrInputField)o;- if (sif.getValueCount() == 0) {- sdoc.remove(sif.getName());- }- }- }- ***/+ private void parseFieldValue(SolrInputField sif) throws IOException {+ int ev = parser.nextEvent();+ if (ev == JSONParser.OBJECT_START) {+ parseExtendedFieldValue(sif, ev);+ } else {+ Object val = parseNormalFieldValue(ev);+ sif.setValue(val, 1.0f);+ }+ }- addValToField(stack, null, inArray, parser);- break;+ private void parseExtendedFieldValue(SolrInputField sif, int ev) throws IOException {+ assert ev == JSONParser.OBJECT_START;- case JSONParser.OBJECT_START:- if( stack.isEmpty() ) {- stack.push( new SolrInputDocument() );- }- else {- obj = stack.peek();- if( obj instanceof SolrInputField ) {- // should alreay be pushed...+ float boost = 1.0f;+ Object normalFieldValue = null;+ Map<String, Object> extendedInfo = null;++ for (;;) {+ ev = parser.nextEvent();+ switch (ev) {+ case JSONParser.STRING:+ String label = parser.getString();+ if ("boost".equals(label)) {+ ev = parser.nextEvent();+ if( ev != JSONParser.NUMBER &&+ ev != JSONParser.LONG &&+ ev != JSONParser.BIGNUMBER ) {+ throw new SolrException(SolrException.ErrorCode.BAD_REQUEST, "boost should have number! "+JSONParser.getEventString(ev) );}- else {- throw new SolrException(SolrException.ErrorCode.BAD_REQUEST, "should not start new object with: "+obj + " ["+ parser.getPosition()+"]" );++ boost = (float)parser.getDouble();+ } else if ("value".equals(label)) {+ normalFieldValue = parseNormalFieldValue(parser.nextEvent());+ } else {+ // If we encounter other unknown map keys, then use a map+ if (extendedInfo == null) {+ extendedInfo = new HashMap<String, Object>(2);}+ // for now, the only extended info will be field values+ // we could either store this as an Object or a SolrInputField+ Object val = parseNormalFieldValue(parser.nextEvent());+ extendedInfo.put(label, val);}break;+case JSONParser.OBJECT_END:- obj = stack.pop();- if( obj instanceof SolrInputDocument ) {- return (SolrInputDocument)obj;- }- else if( obj instanceof SolrInputField ) {- // should already be pushed...- }- else {- throw new SolrException(SolrException.ErrorCode.BAD_REQUEST, "should not start new object with: "+obj + " ["+ parser.getPosition()+"]" );+ if (extendedInfo != null) {+ if (normalFieldValue != null) {+ extendedInfo.put("value",normalFieldValue);+ }+ sif.setValue(extendedInfo, boost);+ } else {+ sif.setValue(normalFieldValue, boost);}- break;+ return;- case JSONParser.ARRAY_START:- inArray = true;- break;-- case JSONParser.ARRAY_END:- inArray = false;- stack.pop(); // the val should have done it...- break;-default:- System.out.println("UNKNOWN_EVENT_ID:"+ev);- break;+ throw new SolrException(SolrException.ErrorCode.BAD_REQUEST, "Error parsing JSON extended field value. Unexpected "+JSONParser.getEventString(ev) );}+ }+ }- ev = parser.nextEvent();- if( ev == JSONParser.EOF ) {- throw new SolrException(SolrException.ErrorCode.BAD_REQUEST, "should finish doc first!" );- }++ private Object parseNormalFieldValue(int ev) throws IOException {+ if (ev == JSONParser.ARRAY_START) {+ List<Object> val = parseArrayFieldValue(ev);+ return val;+ } else {+ Object val = parseSingleFieldValue(ev);+ return val;}}-- static void addValToField( Stack stack, Object val, boolean inArray, JSONParser parser ) throws IOException- {- Object obj = stack.peek();- if( !(obj instanceof SolrInputField) ) {- throw new SolrException(SolrException.ErrorCode.BAD_REQUEST, "hymmm ["+parser.getPosition()+"]" );+++ private Object parseSingleFieldValue(int ev) throws IOException {+ switch (ev) {+ case JSONParser.STRING:+ return parser.getString();+ case JSONParser.LONG:+ case JSONParser.NUMBER:+ case JSONParser.BIGNUMBER:+ return parser.getNumberChars().toString();+ case JSONParser.BOOLEAN:+ return Boolean.toString(parser.getBoolean()); // for legacy reasons, single values s are expected to be strings+ case JSONParser.NULL:+ parser.getNull();+ return null;+ case JSONParser.ARRAY_START:+ return parseArrayFieldValue(ev);+ default:+ throw new SolrException(SolrException.ErrorCode.BAD_REQUEST, "Error parsing JSON field value. Unexpected "+JSONParser.getEventString(ev) );}+ }- SolrInputField f = inArray- ? (SolrInputField)obj- : (SolrInputField)stack.pop();- if (val == null) return;+ private List<Object> parseArrayFieldValue(int ev) throws IOException {+ assert ev == JSONParser.ARRAY_START;- float boost = (f.getValue()==null)?f.getBoost():1.0f;- f.addValue( val,boost );+ ArrayList lst = new ArrayList(2);+ for (;;) {+ ev = parser.nextEvent();+ if (ev == JSONParser.ARRAY_END) {+ return lst;+ }+ Object val = parseSingleFieldValue(ev);+ lst.add(val);+ }}diff --git a/solr/core/src/java/org/apache/solr/handler/RequestHandlerBase.java b/solr/core/src/java/org/apache/solr/handler/RequestHandlerBase.javaindex 0a1f0de07f5..2a533f0bb46 100644--- a/solr/core/src/java/org/apache/solr/handler/RequestHandlerBase.java+++ b/solr/core/src/java/org/apache/solr/handler/RequestHandlerBase.java@@ -138,10 +138,21 @@ public abstract class RequestHandlerBase implements SolrRequestHandler, SolrInfo}}} catch (Exception e) {- SolrException.log(SolrCore.log,e);- if (e instanceof ParseException) {- e = new SolrException(SolrException.ErrorCode.BAD_REQUEST, e);+ if (e instanceof SolrException) {+ SolrException se = (SolrException)e;+ if (se.code() == SolrException.ErrorCode.CONFLICT.code) {+ // TODO: should we allow this to be counted as an error (numErrors++)?++ } else {+ SolrException.log(SolrCore.log,e);+ }+ } else {+ SolrException.log(SolrCore.log,e);+ if (e instanceof ParseException) {+ e = new SolrException(SolrException.ErrorCode.BAD_REQUEST, e);+ }}+rsp.setException(e);numErrors++;}diff --git a/solr/core/src/java/org/apache/solr/handler/XMLLoader.java b/solr/core/src/java/org/apache/solr/handler/XMLLoader.javaindex b27f3e6298d..6898235fe9a 100644--- a/solr/core/src/java/org/apache/solr/handler/XMLLoader.java+++ b/solr/core/src/java/org/apache/solr/handler/XMLLoader.java@@ -42,6 +42,8 @@ import javax.xml.transform.TransformerConfigurationException;import java.io.ByteArrayInputStream;import java.io.InputStream;import java.io.IOException;+import java.util.HashMap;+import java.util.Map;/**@@ -269,6 +271,8 @@ class XMLLoader extends ContentStreamLoader {String name = null;float boost = 1.0f;boolean isNull = false;+ String update = null;+while (true) {int event = parser.next();switch (event) {@@ -283,10 +287,14 @@ class XMLLoader extends ContentStreamLoader {if ("doc".equals(parser.getLocalName())) {return doc;} else if ("field".equals(parser.getLocalName())) {- if (!isNull) {- doc.addField(name, text.toString(), boost);- boost = 1.0f;+ Object v = isNull ? null : text.toString();+ if (update != null) {+ Map<String,Object> extendedValue = new HashMap<String,Object>(1);+ extendedValue.put(update, v);+ v = extendedValue;}+ doc.addField(name, v, boost);+ boost = 1.0f;}break;@@ -299,6 +307,7 @@ class XMLLoader extends ContentStreamLoader {"unexpected XML tag doc/" + localName);}boost = 1.0f;+ update = null;String attrVal = "";for (int i = 0; i < parser.getAttributeCount(); i++) {attrName = parser.getAttributeLocalName(i);@@ -309,6 +318,8 @@ class XMLLoader extends ContentStreamLoader {boost = Float.parseFloat(attrVal);} else if ("null".equals(attrName)) {isNull = StrUtils.parseBoolean(attrVal);+ } else if ("update".equals(attrName)) {+ update = attrVal;} else {XmlUpdateRequestHandler.log.warn("Unknown attribute doc/field/@" + attrName);}diff --git a/solr/core/src/java/org/apache/solr/handler/component/RealTimeGetComponent.java b/solr/core/src/java/org/apache/solr/handler/component/RealTimeGetComponent.javaindex f6e3beff321..0d5f963d918 100644--- a/solr/core/src/java/org/apache/solr/handler/component/RealTimeGetComponent.java+++ b/solr/core/src/java/org/apache/solr/handler/component/RealTimeGetComponent.java@@ -197,6 +197,79 @@ public class RealTimeGetComponent extends SearchComponent}+ public static SolrInputDocument getInputDocument(SolrCore core, BytesRef idBytes) throws IOException {+ SolrInputDocument sid = null;+ RefCounted<SolrIndexSearcher> searcherHolder = null;+ try {+ SolrIndexSearcher searcher = null;+ UpdateLog ulog = core.getUpdateHandler().getUpdateLog();+++ if (ulog != null) {+ Object o = ulog.lookup(idBytes);+ if (o != null) {+ // should currently be a List<Oper,Ver,Doc/Id>+ List entry = (List)o;+ assert entry.size() >= 3;+ int oper = (Integer)entry.get(0);+ switch (oper) {+ case UpdateLog.ADD:+ sid = (SolrInputDocument)entry.get(entry.size()-1);+ break;+ case UpdateLog.DELETE:+ return null;+ default:+ throw new SolrException(SolrException.ErrorCode.SERVER_ERROR, "Unknown Operation! " + oper);+ }+ }+ }++ if (sid == null) {+ // didn't find it in the update log, so it should be in the newest searcher opened+ if (searcher == null) {+ searcherHolder = core.getRealtimeSearcher();+ searcher = searcherHolder.get();+ }++ // SolrCore.verbose("RealTimeGet using searcher ", searcher);+ SchemaField idField = core.getSchema().getUniqueKeyField();++ int docid = searcher.getFirstMatch(new Term(idField.getName(), idBytes));+ if (docid < 0) return null;+ Document luceneDocument = searcher.doc(docid);+ sid = toSolrInputDocument(luceneDocument, core.getSchema());+ }+ } finally {+ if (searcherHolder != null) {+ searcherHolder.decref();+ }+ }++ return sid;+ }++ private static SolrInputDocument toSolrInputDocument(Document doc, IndexSchema schema) {+ SolrInputDocument out = new SolrInputDocument();+ for( IndexableField f : doc.getFields() ) {+ String fname = f.name();+ SchemaField sf = schema.getFieldOrNull(f.name());+ Object val = null;+ if (sf != null) {+ val = sf.getType().toObject(f); // object or external string?+ } else {+ val = f.stringValue();+ if (val == null) val = f.numericValue();+ if (val == null) val = f.binaryValue();+ if (val == null) val = f;+ }++ // todo: how to handle targets of copy fields (including polyfield sub-fields)?+ out.addField(fname, val);+ }+ return out;+ }++private static SolrDocument toSolrDoc(Document doc, IndexSchema schema) {SolrDocument out = new SolrDocument();for( IndexableField f : doc.getFields() ) {@@ -307,7 +380,7 @@ public class RealTimeGetComponent extends SearchComponentsreq.shards = sliceToShards(rb, collection, shard);sreq.actualShards = sreq.shards;sreq.params = new ModifiableSolrParams();- sreq.params.set("shards.qt","/get"); // TODO: how to avoid hardcoding this and hit the same handler?+ sreq.params.set(ShardParams.SHARDS_QT,"/get"); // TODO: how to avoid hardcoding this and hit the same handler?sreq.params.set("distrib",false);sreq.params.set("ids", shardIdList);@@ -321,7 +394,7 @@ public class RealTimeGetComponent extends SearchComponentsreq.shards = null; // ALLsreq.actualShards = sreq.shards;sreq.params = new ModifiableSolrParams();- sreq.params.set("shards.qt","/get"); // TODO: how to avoid hardcoding this and hit the same handler?+ sreq.params.set(ShardParams.SHARDS_QT,"/get"); // TODO: how to avoid hardcoding this and hit the same handler?sreq.params.set("distrib",false);sreq.params.set("ids", shardIdList);diff --git a/solr/core/src/java/org/apache/solr/handler/component/SearchHandler.java b/solr/core/src/java/org/apache/solr/handler/component/SearchHandler.javaindex 4ea471c6386..bf1f8e95e22 100644--- a/solr/core/src/java/org/apache/solr/handler/component/SearchHandler.java+++ b/solr/core/src/java/org/apache/solr/handler/component/SearchHandler.java@@ -266,7 +266,7 @@ public class SearchHandler extends RequestHandlerBase implements SolrCoreAware ,// we could try and detect when this is needed, but it could be trickyparams.set("NOW", Long.toString(rb.requestInfo.getNOW().getTime()));}- String shardQt = req.getParams().get(ShardParams.SHARDS_QT);+ String shardQt = params.get(ShardParams.SHARDS_QT);if (shardQt == null) {params.remove(CommonParams.QT);} else {diff --git a/solr/core/src/java/org/apache/solr/update/processor/DistributedUpdateProcessor.java b/solr/core/src/java/org/apache/solr/update/processor/DistributedUpdateProcessor.javaindex c406b53e99a..622776597a1 100644--- a/solr/core/src/java/org/apache/solr/update/processor/DistributedUpdateProcessor.java+++ b/solr/core/src/java/org/apache/solr/update/processor/DistributedUpdateProcessor.java@@ -31,6 +31,7 @@ import org.apache.solr.cloud.CloudDescriptor;import org.apache.solr.cloud.ZkController;import org.apache.solr.common.SolrException;import org.apache.solr.common.SolrException.ErrorCode;+import org.apache.solr.common.SolrInputDocument;import org.apache.solr.common.SolrInputField;import org.apache.solr.common.cloud.CloudState;import org.apache.solr.common.cloud.Slice;@@ -44,6 +45,7 @@ import org.apache.solr.common.params.UpdateParams;import org.apache.solr.common.util.Hash;import org.apache.solr.common.util.NamedList;import org.apache.solr.core.CoreDescriptor;+import org.apache.solr.handler.component.RealTimeGetComponent;import org.apache.solr.request.SolrQueryRequest;import org.apache.solr.request.SolrRequestInfo;import org.apache.solr.response.SolrQueryResponse;@@ -420,6 +422,24 @@ public class DistributedUpdateProcessor extends UpdateRequestProcessor {long bucketVersion = bucket.highest;if (leaderLogic) {++ boolean updated = getUpdatedDocument(cmd);+ if (updated && versionOnUpdate == -1) {+ versionOnUpdate = 1; // implied "doc must exist" for now...+ }++ if (versionOnUpdate != 0) {+ Long lastVersion = vinfo.lookupVersion(cmd.getIndexedId());+ long foundVersion = lastVersion == null ? -1 : lastVersion;+ if ( versionOnUpdate == foundVersion || (versionOnUpdate < 0 && foundVersion < 0) || (versionOnUpdate==1 && foundVersion > 0) ) {+ // we're ok if versions match, or if both are negative (all missing docs are equal), or if cmd+ // specified it must exist (versionOnUpdate==1) and it does.+ } else {+ throw new SolrException(ErrorCode.CONFLICT, "version conflict for " + cmd.getPrintableId() + " expected=" + versionOnUpdate + " actual=" + foundVersion);+ }+ }++long version = vinfo.getNewClock();cmd.setVersion(version);cmd.getSolrInputDocument().setField(VersionInfo.VERSION_FIELD, version);@@ -459,6 +479,57 @@ public class DistributedUpdateProcessor extends UpdateRequestProcessor {}return false;}+++ // TODO: may want to switch to using optimistic locking in the future for better concurrency+ // that's why this code is here... need to retry in a loop closely around/in versionAdd+ boolean getUpdatedDocument(AddUpdateCommand cmd) throws IOException {+ SolrInputDocument sdoc = cmd.getSolrInputDocument();+ boolean update = false;+ for (SolrInputField sif : sdoc.values()) {+ if (sif.getValue() instanceof Map) {+ update = true;+ break;+ }+ }++ if (!update) return false;++ BytesRef id = cmd.getIndexedId();+ SolrInputDocument oldDoc = RealTimeGetComponent.getInputDocument(cmd.getReq().getCore(), id);++ if (oldDoc == null) {+ // not found... allow this in the future (depending on the details of the update, or if the user explicitly sets it).+ // could also just not change anything here and let the optimistic locking throw the error+ throw new SolrException(ErrorCode.CONFLICT, "Document not found for update. id=" + cmd.getPrintableId());+ }++ oldDoc.remove(VERSION_FIELD);++ for (SolrInputField sif : sdoc.values()) {+ Object val = sif.getValue();+ if (val instanceof Map) {+ for (Entry<String,Object> entry : ((Map<String,Object>) val).entrySet()) {+ String key = entry.getKey();+ Object fieldVal = entry.getValue();+ if ("add".equals(key)) {+ oldDoc.addField( sif.getName(), fieldVal, sif.getBoost());+ } else if ("set".equals(key)) {+ oldDoc.setField(sif.getName(), fieldVal, sif.getBoost());+ }+ }+ } else {+ // normal fields are treated as a "set"+ oldDoc.put(sif.getName(), sif);+ }+ }++ cmd.solrDoc = oldDoc;+ return true;+ }+++@Overridepublic void processDelete(DeleteUpdateCommand cmd) throws IOException {@@ -620,11 +691,8 @@ public class DistributedUpdateProcessor extends UpdateRequestProcessor {cmd.setVersion(-version);// TODO update versions in all buckets- // TODO: flush any adds to these replicas so they do not get reordered w.r.t. this DBQ-doLocalDelete(cmd);-} else {cmd.setVersion(-versionOnUpdate);@@ -709,6 +777,7 @@ public class DistributedUpdateProcessor extends UpdateRequestProcessor {String versionOnUpdateS = req.getParams().get(VERSION_FIELD);versionOnUpdate = versionOnUpdateS == null ? 0 : Long.parseLong(versionOnUpdateS);}+ long signedVersionOnUpdate = versionOnUpdate;versionOnUpdate = Math.abs(versionOnUpdate); // normalize to positive versionboolean isReplay = (cmd.getFlags() & UpdateCommand.REPLAY) != 0;@@ -728,6 +797,18 @@ public class DistributedUpdateProcessor extends UpdateRequestProcessor {long bucketVersion = bucket.highest;if (leaderLogic) {++ if (signedVersionOnUpdate != 0) {+ Long lastVersion = vinfo.lookupVersion(cmd.getIndexedId());+ long foundVersion = lastVersion == null ? -1 : lastVersion;+ if ( (signedVersionOnUpdate == foundVersion) || (signedVersionOnUpdate < 0 && foundVersion < 0) || (signedVersionOnUpdate == 1 && foundVersion > 0) ) {+ // we're ok if versions match, or if both are negative (all missing docs are equal), or if cmd+ // specified it must exist (versionOnUpdate==1) and it does.+ } else {+ throw new SolrException(ErrorCode.CONFLICT, "version conflict for " + cmd.getId() + " expected=" + signedVersionOnUpdate + " actual=" + foundVersion);+ }+ }+long version = vinfo.getNewClock();cmd.setVersion(-version);bucket.updateHighest(version);diff --git a/solr/core/src/test/org/apache/solr/cloud/BasicDistributedZkTest.java b/solr/core/src/test/org/apache/solr/cloud/BasicDistributedZkTest.javaindex ec41a00ca21..bdd07b81ecb 100644--- a/solr/core/src/test/org/apache/solr/cloud/BasicDistributedZkTest.java+++ b/solr/core/src/test/org/apache/solr/cloud/BasicDistributedZkTest.java@@ -35,7 +35,11 @@ import java.util.concurrent.ThreadPoolExecutor;import java.util.concurrent.TimeUnit;import org.apache.lucene.util.LuceneTestCase;+import org.apache.noggit.JSONUtil;+import org.apache.noggit.ObjectBuilder;+import org.apache.solr.JSONTestUtil;import org.apache.solr.client.solrj.SolrQuery;+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.impl.CloudSolrServer;@@ -45,6 +49,7 @@ import org.apache.solr.client.solrj.request.ContentStreamUpdateRequest;import org.apache.solr.client.solrj.request.CoreAdminRequest.Create;import org.apache.solr.client.solrj.request.QueryRequest;import org.apache.solr.client.solrj.response.QueryResponse;+import org.apache.solr.common.SolrException;import org.apache.solr.common.SolrInputDocument;import org.apache.solr.common.cloud.Slice;import org.apache.solr.common.cloud.ZkStateReader;@@ -57,7 +62,7 @@ import org.apache.solr.util.DefaultSolrThreadFactory;/****/[email protected](bugUrl = "https://issues.apache.org/jira/browse/SOLR-2161")+// @LuceneTestCase.AwaitsFix(bugUrl = "https://issues.apache.org/jira/browse/SOLR-2161")public class BasicDistributedZkTest extends AbstractDistributedZkTestCase {private static final String DEFAULT_COLLECTION = "collection1";@@ -274,7 +279,9 @@ public class BasicDistributedZkTest extends AbstractDistributedZkTestCase {// TODO: This test currently fails because debug info is obtained only// on shards with matches.// query("q","matchesnothing","fl","*,score", "debugQuery", "true");-+++ doOptimisticLockingAndUpdating();testMultipleCollections();testANewCollectionInOneInstance();testSearchByCollectionName();@@ -287,6 +294,45 @@ public class BasicDistributedZkTest extends AbstractDistributedZkTestCase {}}+ // cloud level test mainly needed just to make sure that versions and errors are propagated correctly+ private void doOptimisticLockingAndUpdating() throws Exception {+ SolrInputDocument sd = sdoc("id", 1000, "_version_", -1);+ indexDoc(sd);++ ignoreException("version conflict");+ for (SolrServer client : clients) {+ try {+ client.add(sd);+ fail();+ } catch (SolrException e) {+ assertEquals(409, e.code());+ }+ }+ unIgnoreException("version conflict");++ // TODO: test deletes. SolrJ needs a good way to pass version for delete...++ sd = sdoc("id", 1000, "foo_i",5);+ clients.get(0).add(sd);++ List<Integer> expected = new ArrayList<Integer>();+ int val = 0;+ for (SolrServer client : clients) {+ val += 10;+ client.add(sdoc("id", 1000, "val_i", map("add",val), "foo_i",val));+ expected.add(val);+ }++ QueryRequest qr = new QueryRequest(params("qt", "/get", "id","1000"));+ for (SolrServer client : clients) {+ val += 10;+ NamedList rsp = client.request(qr);+ String match = JSONTestUtil.matchObj("/val_i", rsp.get("doc"), expected);+ if (match != null) throw new RuntimeException(match);+ }+ }++private void testNumberOfCommitsWithCommitAfterAdd()throws MalformedURLException, SolrServerException, IOException {long startCommits = getNumCommits((HttpSolrServer) clients.get(0));diff --git a/solr/core/src/test/org/apache/solr/handler/JsonLoaderTest.java b/solr/core/src/test/org/apache/solr/handler/JsonLoaderTest.javaindex 83e692dd291..90b2e8b048a 100644--- a/solr/core/src/test/org/apache/solr/handler/JsonLoaderTest.java+++ b/solr/core/src/test/org/apache/solr/handler/JsonLoaderTest.java@@ -30,6 +30,8 @@ import org.apache.solr.update.processor.BufferingRequestProcessor;import org.junit.BeforeClass;import org.junit.Test;+import java.util.Map;+public class JsonLoaderTest extends SolrTestCaseJ4 {@BeforeClasspublic static void beforeTests() throws Exception {@@ -201,6 +203,31 @@ public class JsonLoaderTest extends SolrTestCaseJ4 {req.close();}+ public void testExtendedFieldValues() throws Exception {+ String str = "[{'id':'1', 'val_s':{'add':'foo'}}]".replace('\'', '"');+ SolrQueryRequest req = req();+ SolrQueryResponse rsp = new SolrQueryResponse();+ BufferingRequestProcessor p = new BufferingRequestProcessor(null);+ JsonLoader loader = new JsonLoader( req, p );+ loader.load(req, rsp, new ContentStreamBase.StringStream(str));++ assertEquals( 1, p.addCommands.size() );++ AddUpdateCommand add = p.addCommands.get(0);+ assertEquals(add.commitWithin, -1);+ assertEquals(add.overwrite, true);+ SolrInputDocument d = add.solrDoc;++ SolrInputField f = d.getField( "id" );+ assertEquals("1", f.getValue());++ f = d.getField( "val_s" );+ Map<String,Object> map = (Map<String,Object>)f.getValue();+ assertEquals("foo",map.get("add"));++ req.close();+ }+@Testpublic void testNullValues() throws Exception {updateJ("[{'id':'10','foo_s':null,'foo2_s':['hi',null,'there']}]".replace('\'', '"'), params("commit","true"));diff --git a/solr/core/src/test/org/apache/solr/search/TestRealTimeGet.java b/solr/core/src/test/org/apache/solr/search/TestRealTimeGet.javaindex 0feb94a7ca9..9aa52c3157b 100644--- a/solr/core/src/test/org/apache/solr/search/TestRealTimeGet.java+++ b/solr/core/src/test/org/apache/solr/search/TestRealTimeGet.java@@ -220,40 +220,171 @@ public class TestRealTimeGet extends SolrTestCaseJ4 {}+ @Test+ public void testOptimisticLocking() throws Exception {+ clearIndex();+ assertU(commit());+ long version = addAndGetVersion(sdoc("id","1") , null);+ long version2;- /***- @Test- public void testGetRealtime() throws Exception {- SolrQueryRequest sr1 = req("q","foo");- IndexReader r1 = sr1.getCore().getRealtimeReader();+ try {+ // try version added directly on doc+ version2 = addAndGetVersion(sdoc("id","1", "_version_", Long.toString(version-1)), null);+ fail();+ } catch (SolrException se) {+ assertEquals(409, se.code());+ }- assertU(adoc("id","1"));+ try {+ // try version added as a parameter on the request+ version2 = addAndGetVersion(sdoc("id","1"), params("_version_", Long.toString(version-1)));+ fail();+ } catch (SolrException se) {+ assertEquals(409, se.code());+ }- IndexReader r2 = sr1.getCore().getRealtimeReader();- assertNotSame(r1, r2);- int refcount = r2.getRefCount();+ try {+ // try an add specifying a negative version+ version2 = addAndGetVersion(sdoc("id","1"), params("_version_", Long.toString(-version)));+ fail();+ } catch (SolrException se) {+ assertEquals(409, se.code());+ }- // make sure a new reader wasn't opened- IndexReader r3 = sr1.getCore().getRealtimeReader();- assertSame(r2, r3);- assertEquals(refcount+1, r3.getRefCount());+ try {+ // try an add with a greater version+ version2 = addAndGetVersion(sdoc("id","1"), params("_version_", Long.toString(version+random().nextInt(1000)+1)));+ fail();+ } catch (SolrException se) {+ assertEquals(409, se.code());+ }- assertU(commit());+ //+ // deletes+ //++ try {+ // try a delete with version on the request+ version2 = deleteAndGetVersion("1", params("_version_", Long.toString(version-1)));+ fail();+ } catch (SolrException se) {+ assertEquals(409, se.code());+ }++ try {+ // try a delete with a negative version+ version2 = deleteAndGetVersion("1", params("_version_", Long.toString(-version)));+ fail();+ } catch (SolrException se) {+ assertEquals(409, se.code());+ }- // this is not critical, but currently a commit does not refresh the reader- // if nothing has changed- IndexReader r4 = sr1.getCore().getRealtimeReader();- assertEquals(refcount+2, r4.getRefCount());+ try {+ // try a delete with a greater version+ version2 = deleteAndGetVersion("1", params("_version_", Long.toString(version+random().nextInt(1000)+1)));+ fail();+ } catch (SolrException se) {+ assertEquals(409, se.code());+ }+ try {+ // try a delete of a document that doesn't exist, specifying a specific version+ version2 = deleteAndGetVersion("I_do_not_exist", params("_version_", Long.toString(version)));+ fail();+ } catch (SolrException se) {+ assertEquals(409, se.code());+ }- r1.decRef();- r2.decRef();- r3.decRef();- r4.decRef();- sr1.close();+ // try a delete of a document that doesn't exist, specifying that it should not+ version2 = deleteAndGetVersion("I_do_not_exist", params("_version_", Long.toString(-1)));+ assertTrue(version2 < 0);++ // overwrite the document+ version2 = addAndGetVersion(sdoc("id","1", "_version_", Long.toString(version)), null);+ assertTrue(version2 > version);++ try {+ // overwriting the previous version should now fail+ version2 = addAndGetVersion(sdoc("id","1"), params("_version_", Long.toString(version)));+ fail();+ } catch (SolrException se) {+ assertEquals(409, se.code());+ }++ try {+ // deleting the previous version should now fail+ version2 = deleteAndGetVersion("1", params("_version_", Long.toString(version)));+ fail();+ } catch (SolrException se) {+ assertEquals(409, se.code());+ }++ version = version2;++ // deleting the current version should work+ version2 = deleteAndGetVersion("1", params("_version_", Long.toString(version)));++ try {+ // overwriting the previous existing doc should now fail (since it was deleted)+ version2 = addAndGetVersion(sdoc("id","1"), params("_version_", Long.toString(version)));+ fail();+ } catch (SolrException se) {+ assertEquals(409, se.code());+ }++ try {+ // deleting the previous existing doc should now fail (since it was deleted)+ version2 = deleteAndGetVersion("1", params("_version_", Long.toString(version)));+ fail();+ } catch (SolrException se) {+ assertEquals(409, se.code());+ }++ // overwriting a negative version should work+ version2 = addAndGetVersion(sdoc("id","1"), params("_version_", Long.toString(-(version-1))));+ assertTrue(version2 > version);+ version = version2;++ // sanity test that we see the right version via rtg+ assertJQ(req("qt","/get","id","1")+ ,"=={'doc':{'id':'1','_version_':" + version + "}}"+ );}- ***/+++ /***+ @Test+ public void testGetRealtime() throws Exception {+ SolrQueryRequest sr1 = req("q","foo");+ IndexReader r1 = sr1.getCore().getRealtimeReader();++ assertU(adoc("id","1"));++ IndexReader r2 = sr1.getCore().getRealtimeReader();+ assertNotSame(r1, r2);+ int refcount = r2.getRefCount();++ // make sure a new reader wasn't opened+ IndexReader r3 = sr1.getCore().getRealtimeReader();+ assertSame(r2, r3);+ assertEquals(refcount+1, r3.getRefCount());++ assertU(commit());++ // this is not critical, but currently a commit does not refresh the reader+ // if nothing has changed+ IndexReader r4 = sr1.getCore().getRealtimeReader();+ assertEquals(refcount+2, r4.getRefCount());+++ r1.decRef();+ r2.decRef();+ r3.decRef();+ r4.decRef();+ sr1.close();+ }+ ***/final ConcurrentHashMap<Integer,DocInfo> model = new ConcurrentHashMap<Integer,DocInfo>();@@ -293,6 +424,22 @@ public class TestRealTimeGet extends SolrTestCaseJ4 {}}+ private long badVersion(Random rand, long version) {+ if (version > 0) {+ // return a random number not equal to version+ for (;;) {+ long badVersion = rand.nextInt();+ if (badVersion != version && badVersion != 0) return badVersion;+ }+ }++ // if the version does not exist, then we can only specify a positive version+ for (;;) {+ long badVersion = rand.nextInt() & 0x7fffffff; // mask off sign bit+ if (badVersion != 0) return badVersion;+ }+ }+@Testpublic void testStressGetRealtime() throws Exception {clearIndex();@@ -304,6 +451,8 @@ public class TestRealTimeGet extends SolrTestCaseJ4 {final int softCommitPercent = 30+random().nextInt(75); // what percent of the commits are softfinal int deletePercent = 4+random().nextInt(25);final int deleteByQueryPercent = 1+random().nextInt(5);+ final int optimisticPercent = 1+random().nextInt(50); // percent change that an update uses optimistic locking+ final int optimisticCorrectPercent = 25+random().nextInt(70); // percent change that a version specified will be correctfinal int ndocs = 5 + (random().nextBoolean() ? random().nextInt(25) : random().nextInt(200));int nWriteThreads = 5 + random().nextInt(25);@@ -400,14 +549,40 @@ public class TestRealTimeGet extends SolrTestCaseJ4 {long nextVal = Math.abs(val)+1;if (oper < commitPercent + deletePercent) {+ boolean opt = rand.nextInt() < optimisticPercent;+ boolean correct = opt ? rand.nextInt() < optimisticCorrectPercent : false;+ long badVersion = correct ? 0 : badVersion(rand, info.version);+if (VERBOSE) {- verbose("deleting id",id,"val=",nextVal);+ if (!opt) {+ verbose("deleting id",id,"val=",nextVal);+ } else {+ verbose("deleting id",id,"val=",nextVal, "existing_version=",info.version, (correct ? "" : (" bad_version=" + badVersion)));+ }}// assertU("<delete><id>" + id + "</id></delete>");- Long version = deleteAndGetVersion(Integer.toString(id), null);+ Long version = null;++ if (opt) {+ if (correct) {+ version = deleteAndGetVersion(Integer.toString(id), params("_version_", Long.toString(info.version)));+ } else {+ try {+ version = deleteAndGetVersion(Integer.toString(id), params("_version_", Long.toString(badVersion)));+ fail();+ } catch (SolrException se) {+ assertEquals(409, se.code());+ }+ }+ } else {+ version = deleteAndGetVersion(Integer.toString(id), null);+ }++ if (version != null) {+ model.put(id, new DocInfo(version, -nextVal));+ }- model.put(id, new DocInfo(version, -nextVal));if (VERBOSE) {verbose("deleting id", id, "val=",nextVal,"DONE");}@@ -422,13 +597,40 @@ public class TestRealTimeGet extends SolrTestCaseJ4 {verbose("deleteByQuery id",id, "val=",nextVal,"DONE");}} else {+ boolean opt = rand.nextInt() < optimisticPercent;+ boolean correct = opt ? rand.nextInt() < optimisticCorrectPercent : false;+ long badVersion = correct ? 0 : badVersion(rand, info.version);+if (VERBOSE) {- verbose("adding id", id, "val=", nextVal);+ if (!opt) {+ verbose("adding id",id,"val=",nextVal);+ } else {+ verbose("adding id",id,"val=",nextVal, "existing_version=",info.version, (correct ? "" : (" bad_version=" + badVersion)));+ }}- // assertU(adoc("id",Integer.toString(id), field, Long.toString(nextVal)));- Long version = addAndGetVersion(sdoc("id", Integer.toString(id), field, Long.toString(nextVal)), null);- model.put(id, new DocInfo(version, nextVal));+ Long version = null;+ SolrInputDocument sd = sdoc("id", Integer.toString(id), field, Long.toString(nextVal));++ if (opt) {+ if (correct) {+ version = addAndGetVersion(sd, params("_version_", Long.toString(info.version)));+ } else {+ try {+ version = addAndGetVersion(sd, params("_version_", Long.toString(badVersion)));+ fail();+ } catch (SolrException se) {+ assertEquals(409, se.code());+ }+ }+ } else {+ version = addAndGetVersion(sd, null);+ }+++ if (version != null) {+ model.put(id, new DocInfo(version, nextVal));+ }if (VERBOSE) {verbose("adding id", id, "val=", nextVal,"DONE");@@ -443,8 +645,7 @@ public class TestRealTimeGet extends SolrTestCaseJ4 {}} catch (Throwable e) {operations.set(-1L);- SolrException.log(log, e);- fail(e.getMessage());+ throw new RuntimeException(e);}}};@@ -505,12 +706,11 @@ public class TestRealTimeGet extends SolrTestCaseJ4 {}}}- catch (Throwable e) {- operations.set(-1L);- SolrException.log(log, e);- fail(e.getMessage());- }+ catch (Throwable e) {+ operations.set(-1L);+ throw new RuntimeException(e);}+ }};threads.add(thread);@@ -538,6 +738,8 @@ public class TestRealTimeGet extends SolrTestCaseJ4 {final int softCommitPercent = 30+random().nextInt(75); // what percent of the commits are softfinal int deletePercent = 4+random().nextInt(25);final int deleteByQueryPercent = 1 + random().nextInt(5);+ final int optimisticPercent = 1+random().nextInt(50); // percent change that an update uses optimistic locking+ final int optimisticCorrectPercent = 25+random().nextInt(70); // percent change that a version specified will be correctfinal int ndocs = 5 + (random().nextBoolean() ? random().nextInt(25) : random().nextInt(200));int nWriteThreads = 5 + random().nextInt(25);@@ -679,11 +881,10 @@ public class TestRealTimeGet extends SolrTestCaseJ4 {lastId = id;}}- } catch (Throwable e) {- operations.set(-1L);- SolrException.log(log, e);- fail(e.getMessage());- }+ } catch (Throwable e) {+ operations.set(-1L);+ throw new RuntimeException(e);+ }}};@@ -742,11 +943,9 @@ public class TestRealTimeGet extends SolrTestCaseJ4 {}}}- }- catch (Throwable e) {+ } catch (Throwable e) {operations.set(-1L);- SolrException.log(log, e);- fail(e.getMessage());+ throw new RuntimeException(e);}}};@@ -917,11 +1116,10 @@ public class TestRealTimeGet extends SolrTestCaseJ4 {lastId = id;}}- } catch (Throwable e) {- operations.set(-1L);- SolrException.log(log, e);- fail(e.getMessage());- }+ } catch (Throwable e) {+ operations.set(-1L);+ throw new RuntimeException(e);+ }}};@@ -980,11 +1178,9 @@ public class TestRealTimeGet extends SolrTestCaseJ4 {}}}- }- catch (Throwable e) {+ } catch (Throwable e) {operations.set(-1L);- SolrException.log(log, e);- fail(e.getMessage());+ throw new RuntimeException(e);}}};@@ -1189,11 +1385,10 @@ public class TestRealTimeGet extends SolrTestCaseJ4 {lastId = id;}}- } catch (Throwable e) {- operations.set(-1L);- SolrException.log(log, e);- fail(e.getMessage());- }+ } catch (Throwable e) {+ operations.set(-1L);+ throw new RuntimeException(e);+ }}};@@ -1263,12 +1458,10 @@ public class TestRealTimeGet extends SolrTestCaseJ4 {getLatestVersions();// TODO: some sort of validation that the latest version is >= to the latest version we added?}-- }- catch (Throwable e) {++ } catch (Throwable e) {operations.set(-1L);- SolrException.log(log, e);- fail(e.getMessage());+ throw new RuntimeException(e);}}};@@ -1670,11 +1863,9 @@ public class TestRealTimeGet extends SolrTestCaseJ4 {r.decRef();}- }- catch (Throwable e) {+ } catch (Throwable e) {operations.set(-1L);- SolrException.log(log,e);- fail(e.toString());+ throw new RuntimeException(e);}}};diff --git a/solr/core/src/test/org/apache/solr/update/TestUpdate.java b/solr/core/src/test/org/apache/solr/update/TestUpdate.javanew file mode 100644index 00000000000..c63e2d876eb--- /dev/null+++ b/solr/core/src/test/org/apache/solr/update/TestUpdate.java@@ -0,0 +1,165 @@+/**+ * 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.update;+++import org.apache.lucene.analysis.MockAnalyzer;+import org.apache.lucene.document.Document;+import org.apache.lucene.document.Field;+import org.apache.lucene.document.FieldType;+import org.apache.lucene.index.*;+import org.apache.lucene.search.DocIdSetIterator;+import org.apache.lucene.search.TermQuery;+import org.apache.lucene.store.Directory;+import org.apache.lucene.util.BytesRef;+import org.apache.noggit.ObjectBuilder;+import org.apache.solr.SolrTestCaseJ4;+import org.apache.solr.common.SolrException;+import org.apache.solr.common.SolrInputDocument;+import org.apache.solr.request.SolrQueryRequest;+import org.apache.solr.util.TestHarness;+import org.junit.BeforeClass;+import org.junit.Test;++import java.io.IOException;+import java.util.*;+import java.util.concurrent.*;+import java.util.concurrent.atomic.AtomicInteger;+import java.util.concurrent.atomic.AtomicLong;+import java.util.concurrent.locks.Lock;+import java.util.concurrent.locks.ReentrantLock;++import static org.apache.solr.core.SolrCore.verbose;+import static org.apache.solr.update.processor.DistributedUpdateProcessor.SEEN_LEADER;++public class TestUpdate extends SolrTestCaseJ4 {+ @BeforeClass+ public static void beforeClass() throws Exception {+ initCore("solrconfig-tlog.xml","schema15.xml");+ }++ @Test+ public void testUpdateableDocs() throws Exception {+ // The document may be retrieved from the index or from the transaction log.+ // Test both by running the same test with and without commits++ // do without commits+ doUpdateTest(new Callable() {+ @Override+ public Object call() throws Exception {+ return null;+ }+ });++ // do with commits+ doUpdateTest(new Callable() {+ @Override+ public Object call() throws Exception {+ commit("softCommit","false");+ return null;+ }+ });+++ }++ public void doUpdateTest(Callable afterUpdate) throws Exception {+ clearIndex();+ afterUpdate.call();++ long version;++ version = addAndGetVersion(sdoc("id","1", "val_i",5), null);+ afterUpdate.call();+ version = addAndGetVersion(sdoc("id","1", "val_is",map("add",10)), null);+ afterUpdate.call();+ version = addAndGetVersion(sdoc("id","1", "val_is",map("add",5)), null);+ afterUpdate.call();++ assertJQ(req("qt","/get", "id","1", "fl","id,*_i,*_is")+ ,"=={'doc':{'id':'1', 'val_i':5, 'val_is':[10,5]}}"+ );++ version = addAndGetVersion(sdoc("id","1", "val_is",map("add",-1), "val_i",map("set",100)), null);+ afterUpdate.call();++ assertJQ(req("qt","/get", "id","1", "fl","id,*_i,*_is")+ ,"=={'doc':{'id':'1', 'val_i':100, 'val_is':[10,5,-1]}}"+ );+++ long version2;+ try {+ // try bad version added as a field in the doc+ version2 = addAndGetVersion(sdoc("id","1", "val_is",map("add",-100), "_version_",2), null);+ fail();+ } catch (SolrException se) {+ assertEquals(409, se.code());+ }++ try {+ // try bad version added as a request param+ version2 = addAndGetVersion(sdoc("id","1", "val_is",map("add",-100)), params("_version_","2"));+ fail();+ } catch (SolrException se) {+ assertEquals(409, se.code());+ }++ // try good version added as a field in the doc+ version = addAndGetVersion(sdoc("id","1", "val_is",map("add",-100), "_version_",version), null);+ afterUpdate.call();++ // try good version added as a request parameter+ version = addAndGetVersion(sdoc("id","1", "val_is",map("add",-200)), params("_version_",Long.toString(version)));+ afterUpdate.call();++ assertJQ(req("qt","/get", "id","1", "fl","id,*_i,*_is")+ ,"=={'doc':{'id':'1', 'val_i':100, 'val_is':[10,5,-1,-100,-200]}}"+ );++ // extra field should just be treated as a "set"+ version = addAndGetVersion(sdoc("id","1", "val_is",map("add",-300), "val_i",2), null);+ afterUpdate.call();++ assertJQ(req("qt","/get", "id","1", "fl","id,*_i,*_is")+ ,"=={'doc':{'id':'1', 'val_i':2, 'val_is':[10,5,-1,-100,-200,-300]}}"+ );++ // a null value should be treated as "remove"+ version = addAndGetVersion(sdoc("id","1", "val_is",map("add",-400), "val_i",null), null);+ afterUpdate.call();++ assertJQ(req("qt","/get", "id","1", "fl","id,*_i,*_is")+ ,"=={'doc':{'id':'1', 'val_is':[10,5,-1,-100,-200,-300,-400]}}"+ );+++ version = deleteAndGetVersion("1", null);+ afterUpdate.call();++ try {+ // Currently, there is an implicit _version_=1 for updates (doc must exist). This is subject to change!+ version2 = addAndGetVersion(sdoc("id","1", "val_is",map("add",-100)), null);+ fail();+ } catch (SolrException se) {+ assertEquals(409, se.code());+ }+++ }++}diff --git a/solr/solrj/src/java/org/apache/solr/client/solrj/impl/HttpSolrServer.java b/solr/solrj/src/java/org/apache/solr/client/solrj/impl/HttpSolrServer.javaindex 1202a531fd7..41461b3ce5c 100644--- a/solr/solrj/src/java/org/apache/solr/client/solrj/impl/HttpSolrServer.java+++ b/solr/solrj/src/java/org/apache/solr/client/solrj/impl/HttpSolrServer.java@@ -387,6 +387,7 @@ public class HttpSolrServer extends SolrServer {switch (httpStatus) {case HttpStatus.SC_OK:case HttpStatus.SC_BAD_REQUEST:+ case HttpStatus.SC_CONFLICT: // 409break;case HttpStatus.SC_MOVED_PERMANENTLY:case HttpStatus.SC_MOVED_TEMPORARILY:diff --git a/solr/solrj/src/java/org/apache/solr/client/solrj/util/ClientUtils.java b/solr/solrj/src/java/org/apache/solr/client/solrj/util/ClientUtils.javaindex 6353e8332a2..19bcdf31332 100644--- a/solr/solrj/src/java/org/apache/solr/client/solrj/util/ClientUtils.java+++ b/solr/solrj/src/java/org/apache/solr/client/solrj/util/ClientUtils.java@@ -96,10 +96,22 @@ public class ClientUtilsfor( SolrInputField field : doc ) {float boost = field.getBoost();String name = field.getName();+for( Object v : field ) {+ String update = null;++ if (v instanceof Map) {+ // currently only supports a single value+ for (Entry<Object,Object> entry : ((Map<Object,Object>)v).entrySet()) {+ update = entry.getKey().toString();+ Object fieldVal = entry.getValue();+ v = fieldVal;+ }+ }+if (v instanceof Date) {v = DateUtil.getThreadLocalDateFormat().format( (Date)v );- }else if (v instanceof byte[]) {+ } else if (v instanceof byte[]) {byte[] bytes = (byte[]) v;v = Base64.byteArrayToBase64(bytes, 0,bytes.length);} else if (v instanceof ByteBuffer) {@@ -107,10 +119,18 @@ public class ClientUtilsv = Base64.byteArrayToBase64(bytes.array(), bytes.position(),bytes.limit() - bytes.position());}- if( boost != 1.0f ) {- XML.writeXML(writer, "field", v.toString(), "name", name, "boost", boost );- } else if (v != null) {- XML.writeXML(writer, "field", v.toString(), "name", name );+ if (update == null) {+ if( boost != 1.0f ) {+ XML.writeXML(writer, "field", v.toString(), "name", name, "boost", boost );+ } else if (v != null) {+ XML.writeXML(writer, "field", v.toString(), "name", name );+ }+ } else {+ if( boost != 1.0f ) {+ XML.writeXML(writer, "field", v.toString(), "name", name, "boost", boost, "update", update);+ } else if (v != null) {+ XML.writeXML(writer, "field", v.toString(), "name", name, "update", update);+ }}// only write the boost for the first multi-valued fielddiff --git a/solr/solrj/src/java/org/apache/solr/common/SolrException.java b/solr/solrj/src/java/org/apache/solr/common/SolrException.javaindex 9c9c8decef1..1ca7b81bdd3 100644--- a/solr/solrj/src/java/org/apache/solr/common/SolrException.java+++ b/solr/solrj/src/java/org/apache/solr/common/SolrException.java@@ -38,6 +38,7 @@ public class SolrException extends RuntimeException {UNAUTHORIZED( 401 ),FORBIDDEN( 403 ),NOT_FOUND( 404 ),+ CONFLICT( 409 ),SERVER_ERROR( 500 ),SERVICE_UNAVAILABLE( 503 ),UNKNOWN(0);diff --git a/solr/test-framework/src/java/org/apache/solr/SolrTestCaseJ4.java b/solr/test-framework/src/java/org/apache/solr/SolrTestCaseJ4.javaindex af666e5ed4c..8001b00492c 100755--- a/solr/test-framework/src/java/org/apache/solr/SolrTestCaseJ4.java+++ b/solr/test-framework/src/java/org/apache/solr/SolrTestCaseJ4.java@@ -713,6 +713,15 @@ public abstract class SolrTestCaseJ4 extends LuceneTestCase {return msp;}+ public static Map map(Object... params) {+ LinkedHashMap ret = new LinkedHashMap();+ for (int i=0; i<params.length; i+=2) {+ Object o = ret.put(params[i], params[i+1]);+ // TODO: handle multi-valued map?+ }+ return ret;+ }+/*** Generates a SolrQueryRequest using the LocalRequestFactory* @see #lrf@@ -810,17 +819,18 @@ public abstract class SolrTestCaseJ4 extends LuceneTestCase {else out.append(',');JSONUtil.writeString(sfield.getName(), 0, sfield.getName().length(), out);out.append(':');+if (sfield.getValueCount() > 1) {out.append('[');- }- boolean firstVal = true;- for (Object val : sfield) {- if (firstVal) firstVal=false;- else out.append(',');- out.append(JSONUtil.toJSON(val));- }- if (sfield.getValueCount() > 1) {+ boolean firstVal = true;+ for (Object val : sfield) {+ if (firstVal) firstVal=false;+ else out.append(',');+ out.append(JSONUtil.toJSON(val));+ }out.append(']');+ } else {+ out.append(JSONUtil.toJSON(sfield.getValue()));}}out.append('}');