Java Code Examples for org.apache.solr.client.solrj.response.UpdateResponse#getStatus()

The following examples show how to use org.apache.solr.client.solrj.response.UpdateResponse#getStatus() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: SolrController.java    From Spring-Boot-Book with Apache License 2.0 6 votes vote down vote up
@RequestMapping("/delById/{id}")
public String delById(@PathVariable("id") String id) throws IOException, SolrServerException {
    //根据id删除信息
    UpdateResponse updateResponse = solrClient.deleteById(id);
    //执行的时间
    long elapsedTime = updateResponse.getElapsedTime();

    int qTime = updateResponse.getQTime();
    //请求地址
    String requestUrl = updateResponse.getRequestUrl();
    //请求的结果{responseHeader={status=0,QTime=2}}
    NamedList<Object> response = updateResponse.getResponse();
    //请求结果的头{status=0,QTime=2}
    NamedList responseHeader = updateResponse.getResponseHeader();
    //请求的状态 0
    solrClient.commit();
    int status = updateResponse.getStatus();
    //成功则返回0.要是没有文档被删除也会返回0,代表根本没有
    return status == 0 ? "success" : "failed";
}
 
Example 2
Source File: SolrControllerTest.java    From Spring-Boot-Book with Apache License 2.0 6 votes vote down vote up
@Test
public void delById()  throws IOException, SolrServerException {
    //根据id删除信息
    UpdateResponse updateResponse = solrClient.deleteById("8888888");
    //执行的时间
    long elapsedTime = updateResponse.getElapsedTime();
    int qTime = updateResponse.getQTime();
    //请求地址
    String requestUrl = updateResponse.getRequestUrl();
    //请求的结果{responseHeader={status=0,QTime=2}}
    NamedList<Object> response = updateResponse.getResponse();
    //请求结果的头{status=0,QTime=2}
    NamedList responseHeader = updateResponse.getResponseHeader();
    //请求的状态 0
    solrClient.commit();
    int status = updateResponse.getStatus();
    //成功则返回0.要是没有文档被删除也会返回0,代表根本没有

}
 
Example 3
Source File: OutputSolr.java    From ambari-logsearch with Apache License 2.0 5 votes vote down vote up
private void addToSolr(OutputData outputData) throws SolrServerException, IOException {
  UpdateResponse response = solrClient.add(localBuffer);
  if (response.getStatus() != 0) {
    String logMessageKey = this.getClass().getSimpleName() + "_SOLR_UPDATE_ERROR";
    LogFeederUtil.logErrorMessageByInterval(logMessageKey,
        String.format("Error writing to Solr. response=%s, log=%s", response, outputData), null, logger, Level.ERROR);
  }
  statMetric.value += localBuffer.size();
  writeBytesMetric.value += localBufferBytesSize;
  for (InputMarker inputMarker : latestInputMarkers.values()) {
    inputMarker.getInput().checkIn(inputMarker);
  }
}
 
Example 4
Source File: MCRSolrInputDocumentsHandler.java    From mycore with GNU General Public License v3.0 5 votes vote down vote up
@Override
public void index() throws IOException, SolrServerException {
    if (documents == null || documents.isEmpty()) {
        LOGGER.warn("No input documents to index.");
        return;
    }
    int totalCount = documents.size();
    LOGGER.info("Handling {} documents", totalCount);
    SolrClient solrClient = getSolrClient();
    if (solrClient instanceof ConcurrentUpdateSolrClient) {
        LOGGER.info("Detected ConcurrentUpdateSolrClient. Split up batch update.");
        splitDocuments();
        //for statistics:
        documents.clear();
        return;
    }
    UpdateResponse updateResponse;
    try {
        UpdateRequest updateRequest = getUpdateRequest(MCRSolrConstants.SOLR_UPDATE_PATH);
        updateRequest.add(documents);
        updateResponse = updateRequest.process(getSolrClient());
    } catch (Throwable e) {
        LOGGER.warn("Error while indexing document collection. Split and retry.");
        splitDocuments();
        return;
    }
    if (updateResponse.getStatus() != 0) {
        LOGGER.error("Error while indexing document collection. Split and retry: {}", updateResponse.getResponse());
        splitDocuments();
    } else {
        LOGGER.info("Sending {} documents was successful in {} ms.", totalCount, updateResponse.getElapsedTime());
    }
}
 
Example 5
Source File: CdcrReplicator.java    From lucene-solr with Apache License 2.0 5 votes vote down vote up
private void sendRequest(UpdateRequest req) throws IOException, SolrServerException, CdcrReplicatorException {
  UpdateResponse rsp = req.process(state.getClient());
  if (rsp.getStatus() != 0) {
    throw new CdcrReplicatorException(req, rsp);
  }
  state.resetConsecutiveErrors();
}
 
Example 6
Source File: SolrAbstractSink.java    From pulsar with Apache License 2.0 5 votes vote down vote up
@Override
public void write(Record<T> record) {
    UpdateRequest updateRequest = new UpdateRequest();
    if (solrSinkConfig.getSolrCommitWithinMs() > 0) {
        updateRequest.setCommitWithin(solrSinkConfig.getSolrCommitWithinMs());
    }
    if (enableBasicAuth) {
        updateRequest.setBasicAuthCredentials(
            solrSinkConfig.getUsername(),
            solrSinkConfig.getPassword()
        );
    }

    SolrInputDocument document = convert(record);
    updateRequest.add(document);

    try {
        UpdateResponse updateResponse = updateRequest.process(client, solrSinkConfig.getSolrCollection());
        if (updateResponse.getStatus() == 0) {
            record.ack();
        } else {
            record.fail();
        }
    } catch (SolrServerException | IOException e) {
        record.fail();
        log.warn("Solr update document exception ", e);
    }
}
 
Example 7
Source File: SolrWriter.java    From metron with Apache License 2.0 5 votes vote down vote up
protected Optional<SolrException> fromUpdateResponse(UpdateResponse response) {
  if(response != null && response.getStatus() > 0) {
    String message = "Solr Update response: " + Joiner.on(",").join(response.getResponse());
    return Optional.of(new SolrException(SolrException.ErrorCode.BAD_REQUEST, message));
  }
  return Optional.empty();
}
 
Example 8
Source File: DbToSolrMigrationUtil.java    From ranger with Apache License 2.0 5 votes vote down vote up
public void send2solr(XXAccessAuditV4 xXAccessAudit) throws Throwable {
	SolrInputDocument document = new SolrInputDocument();
	toSolrDocument(xXAccessAudit,document);
	UpdateResponse response = solrClient.add(document);
	if (response.getStatus() != 0) {
		logger.info("Response=" + response.toString() + ", status= "
				+ response.getStatus() + ", event=" + xXAccessAudit.toString());
		throw new Exception("Failed to send audit event ID=" + xXAccessAudit.getId());
	}
}
 
Example 9
Source File: DbToSolrMigrationUtil.java    From ranger with Apache License 2.0 5 votes vote down vote up
public void send2solr(XXAccessAuditV5 xXAccessAudit) throws Throwable {
	SolrInputDocument document = new SolrInputDocument();
	toSolrDocument(xXAccessAudit,document);
	UpdateResponse response = solrClient.add(document);
	if (response.getStatus() != 0) {
		logger.info("Response=" + response.toString() + ", status= "
				+ response.getStatus() + ", event=" + xXAccessAudit.toString());
		throw new Exception("Failed to send audit event ID=" + xXAccessAudit.getId());
	}
}
 
Example 10
Source File: DbToSolrMigrationUtil.java    From ranger with Apache License 2.0 5 votes vote down vote up
public void send2solr(XXAccessAudit xXAccessAudit) throws Throwable {
	SolrInputDocument document = new SolrInputDocument();
	toSolrDocument(xXAccessAudit,document);
	UpdateResponse response = solrClient.add(document);
	if (response.getStatus() != 0) {
		logger.info("Response=" + response.toString() + ", status= "
				+ response.getStatus() + ", event=" + xXAccessAudit.toString());
		throw new Exception("Failed to send audit event ID=" + xXAccessAudit.getId());
	}
}
 
Example 11
Source File: MCRSolrMCRContentMapIndexHandler.java    From mycore with GNU General Public License v3.0 4 votes vote down vote up
@Override
public void index() throws IOException, SolrServerException {
    int totalCount = contentMap.size();
    LOGGER.info("Handling {} documents", totalCount);
    //multithread processing will result in too many http request
    UpdateResponse updateResponse;
    try {
        Iterator<SolrInputDocument> documents = MCRSolrInputDocumentFactory.getInstance().getDocuments(contentMap);
        SolrClient solrClient = getSolrClient();
        if (solrClient instanceof ConcurrentUpdateSolrClient) {
            //split up to speed up processing
            splitup(documents);
            return;
        }
        if (LOGGER.isDebugEnabled()) {
            ArrayList<SolrInputDocument> debugList = new ArrayList<>();
            while (documents.hasNext()) {
                debugList.add(documents.next());
            }
            LOGGER.debug("Sending these documents: {}", debugList);
            //recreate documents interator;
            documents = debugList.iterator();
        }
        if (solrClient instanceof HttpSolrClient) {
            updateResponse = solrClient.add(documents);
        } else {
            ArrayList<SolrInputDocument> docs = new ArrayList<>(totalCount);
            while (documents.hasNext()) {
                docs.add(documents.next());
            }
            updateResponse = solrClient.add(docs);
        }
    } catch (Throwable e) {
        LOGGER.warn("Error while indexing document collection. Split and retry.", e);
        splitup();
        return;
    }
    if (updateResponse.getStatus() != 0) {
        LOGGER.error("Error while indexing document collection. Split and retry: {}", updateResponse.getResponse());
        splitup();
    } else {
        LOGGER.info("Sending {} documents was successful in {} ms.", totalCount, updateResponse.getElapsedTime());
    }

}
 
Example 12
Source File: SolrAddingService.java    From chronix.server with Apache License 2.0 4 votes vote down vote up
private static boolean evaluate(UpdateResponse response) {
    LOGGER.debug("Response returned: Status code {}, Elapsed time {}, QTime {}", response.getStatus(), response.getElapsedTime(), response.getQTime());
    //any other status code means 'there was an error'
    return response.getStatus() == 0;
}
 
Example 13
Source File: SolrComponent.java    From metron with Apache License 2.0 4 votes vote down vote up
protected void checkUpdateResponse(UpdateResponse result) throws IOException {
  if (result.getStatus() != 0) {
    throw new IOException("Response error received while adding documents: " + result);
  }
}
 
Example 14
Source File: SolrAuditProvider.java    From ranger with Apache License 2.0 4 votes vote down vote up
@Override
public boolean log(AuditEventBase event) {
	if (!(event instanceof AuthzAuditEvent)) {
		LOG.error(event.getClass().getName()
				+ " audit event class type is not supported");
		return false;
	}
	AuthzAuditEvent authzEvent = (AuthzAuditEvent) event;
	// TODO: This should be done at a higher level

	if (authzEvent.getAgentHostname() == null) {
		authzEvent.setAgentHostname(MiscUtil.getHostname());
	}

	if (authzEvent.getLogType() == null) {
		authzEvent.setLogType("RangerAudit");
	}

	if (authzEvent.getEventId() == null) {
		authzEvent.setEventId(MiscUtil.generateUniqueId());
	}

	try {
		if (solrClient == null) {
			connect();
			if (solrClient == null) {
				// Solr is still not initialized. So need to throw error
				return false;
			}
		}

		if (lastFailTime > 0) {
			long diff = System.currentTimeMillis() - lastFailTime;
			if (diff < retryWaitTime) {
				if (LOG.isDebugEnabled()) {
					LOG.debug("Ignore sending audit. lastConnect=" + diff
							+ " ms");
				}
				return false;
			}
		}
		// Convert AuditEventBase to Solr document
		final SolrInputDocument document = toSolrDoc(authzEvent);
		final Collection<SolrInputDocument> docs = Collections.singletonList(document);
		final UpdateResponse response = SolrAppUtil.addDocsToSolr(solrClient, docs);

		if (response.getStatus() != 0) {
			lastFailTime = System.currentTimeMillis();

			// System.out.println("Response=" + response.toString()
			// + ", status= " + response.getStatus() + ", event="
			// + event);
			// throw new Exception("Aborting. event=" + event +
			// ", response="
			// + response.toString());
		} else {
			lastFailTime = 0;
		}

	} catch (Throwable t) {
		LOG.error("Error sending message to Solr", t);
		return false;
	}
	return true;
}
 
Example 15
Source File: SolrAuditDestination.java    From ranger with Apache License 2.0 4 votes vote down vote up
@Override
public boolean log(Collection<AuditEventBase> events) {
	boolean ret = false;
	try {
		logStatusIfRequired();
		addTotalCount(events.size());

		if (solrClient == null) {
			connect();
			if (solrClient == null) {
				// Solr is still not initialized. So need return error
				addDeferredCount(events.size());
				return ret;
			}
		}

		final Collection<SolrInputDocument> docs = new ArrayList<SolrInputDocument>();
		for (AuditEventBase event : events) {
			AuthzAuditEvent authzEvent = (AuthzAuditEvent) event;
			// Convert AuditEventBase to Solr document
			SolrInputDocument document = toSolrDoc(authzEvent);
			docs.add(document);
		}
		try {
			final UpdateResponse response = SolrAppUtil.addDocsToSolr(solrClient, docs);

			if (response.getStatus() != 0) {
				addFailedCount(events.size());
				logFailedEvent(events, response.toString());
			} else {
				addSuccessCount(events.size());
				ret = true;
			}
		} catch (SolrException ex) {
			addFailedCount(events.size());
			logFailedEvent(events, ex);
		}
	} catch (Throwable t) {
		addDeferredCount(events.size());
		logError("Error sending message to Solr", t);
	}
	return ret;
}