Apache Nutch is an extensible and scalable web crawler
working elasticsearch rest
brianzhao6f9a8f3e5598
diff --git a/build.xml b/build.xmlindex 0ee60a155..e2f9754f7 100644--- a/build.xml+++ b/build.xml@@ -187,6 +187,7 @@<packageset dir="${plugins.dir}/mimetype-filter/src/java"/><packageset dir="${plugins.dir}/indexer-dummy/src/java"/><packageset dir="${plugins.dir}/indexer-elastic/src/java/" />+ <packageset dir="${plugins.dir}/indexer-elastic-rest/src/java/"/><packageset dir="${plugins.dir}/indexer-solr/src/java"/><packageset dir="${plugins.dir}/language-identifier/src/java"/><packageset dir="${plugins.dir}/lib-htmlunit/src/java"/>@@ -631,6 +632,7 @@<packageset dir="${plugins.dir}/mimetype-filter/src/java"/><packageset dir="${plugins.dir}/indexer-dummy/src/java"/><packageset dir="${plugins.dir}/indexer-elastic/src/java/" />+ <packageset dir="${plugins.dir}/indexer-elastic-rest/src/java/"/><packageset dir="${plugins.dir}/indexer-solr/src/java"/><packageset dir="${plugins.dir}/language-identifier/src/java"/><packageset dir="${plugins.dir}/lib-htmlunit/src/java"/>@@ -1033,6 +1035,7 @@<source path="${plugins.dir}/indexer-solr/src/java/" /><source path="${plugins.dir}/indexer-elastic/src/java/" /><source path="${plugins.dir}/indexer-elastic/src/test/" />+ <source path="${plugins.dir}/indexer-elastic-rest/src/java/"/><source path="${plugins.dir}/index-metadata/src/java/" /><source path="${plugins.dir}/index-more/src/java/" /><source path="${plugins.dir}/index-more/src/test/" />diff --git a/conf/log4j.properties b/conf/log4j.propertiesindex ca715f3d5..d5d5f7525 100644--- a/conf/log4j.properties+++ b/conf/log4j.properties@@ -114,3 +114,7 @@ log4j.appender.cmdstdout.layout.ConversionPattern=%m%n#log4j.appender.RFA.layout.ConversionPattern=%d{ISO8601} %-5p %c{2} - %m%n#log4j.appender.RFA.layout.ConversionPattern=%d{ISO8601} %-5p %c{2} (%F:%M(%L)) - %m%n+#+# Plugin-Specific Loggers+#+#log4j.logger.org.apache.nutch.indexwriter.elasticrest.ElasticRestIndexWriter=INFO,cmdstdout\ No newline at end of filediff --git a/conf/nutch-default.xml b/conf/nutch-default.xmlindex 67326eed9..66d9c91e7 100644--- a/conf/nutch-default.xml+++ b/conf/nutch-default.xml@@ -1868,6 +1868,78 @@ visit https://wiki.apache.org/nutch/SimilarityScoringFilter-->last operation.</description></property>+<!--elasticsearch rest properties-->+<property>+ <name>elastic.rest.host</name>+ <value></value>+ <description>The hostname to send documents to using Elasticsearch Jest. Both host+ and port must be defined</description>+</property>++<property>+ <name>elastic.rest.port</name>+ <value></value>+ <description>The port to connect to using Elasticsearch Jest.</description>+</property>++<property>+ <name>elastic.rest.index</name>+ <value>nutch</value>+ <description>Default index to send documents to.</description>+</property>++<property>+ <name>elastic.rest.type</name>+ <value>doc</value>+ <description>Default type to send documents to.</description>+</property>++<property>+ <name>elastic.rest.max.bulk.docs</name>+ <value>250</value>+ <description>Maximum size of the bulk in number of documents.</description>+</property>++<property>+ <name>elastic.rest.max.bulk.size</name>+ <value>26214400</value>+ <description>Maximum size of the bulk in bytes.</description>+</property>++<property>+ <name>elastic.rest.https</name>+ <value>false</value>+ <description>+ "true" to enable https, "false" to disable https+ If you've disabled http access (by forcing https), be sure to+ set this to true, otherwise you might get "connection reset by peer".+ </description>+</property>++<property>+ <name>elastic.rest.user</name>+ <value></value>+ <description>Username for auth credentials (only used when https is enabled)</description>+</property>++<property>+ <name>elastic.rest.password</name>+ <value></value>+ <description>Password for auth credentials (only used when https is enabled)</description>+</property>++<property>+ <name>elastic.rest.trustallhostnames</name>+ <value>false</value>+ <description>+ "true" to trust elasticsearch server's certificate even if its listed domain name does not+ match the domain they are hosted on+ "false" to check if the elasticsearch server's certificate's listed domain is the same domain+ that it is hosted on, and if it doesn't, then fail to index+ (only used when https is enabled)+ </description>+</property>+<!-- subcollection properties --><property>diff --git a/ivy/ivy.xml b/ivy/ivy.xmlindex a9a83ae46..8e048fa3c 100644--- a/ivy/ivy.xml+++ b/ivy/ivy.xml@@ -128,6 +128,13 @@<dependency org="de.agilecoders.wicket" name="wicket-bootstrap-core" rev="0.9.2" conf="*->default" /><dependency org="de.agilecoders.wicket" name="wicket-bootstrap-extensions" rev="0.9.2" conf="*->default" />++ <!--Added Because of Elasticsearch JEST client-->+ <!--TODO refactor these to indexer-elastic-rest plugin somehow, currently doesn't resolve correctly-->+ <dependency org="org.apache.httpcomponents" name="httpcore-nio" rev="4.4.4"/>+ <dependency org="org.apache.httpcomponents" name="httpcore" rev="4.4.4"/>+ <dependency org="org.apache.httpcomponents" name="httpclient" rev="4.5.2"/>+<!--global exclusion --><exclude module="jmxtools" /><exclude module="jms" />diff --git a/src/plugin/build.xml b/src/plugin/build.xmlindex 20ef870e8..8ff74002d 100755--- a/src/plugin/build.xml+++ b/src/plugin/build.xml@@ -41,6 +41,7 @@<ant dir="indexer-cloudsearch" target="deploy"/><ant dir="indexer-dummy" target="deploy"/><ant dir="indexer-elastic" target="deploy"/>+ <ant dir="indexer-elastic-rest" target="deploy"/><ant dir="indexer-solr" target="deploy"/><ant dir="language-identifier" target="deploy"/><ant dir="lib-http" target="deploy"/>@@ -159,6 +160,7 @@<ant dir="indexer-cloudsearch" target="clean"/><ant dir="indexer-dummy" target="clean"/><ant dir="indexer-elastic" target="clean"/>+ <ant dir="indexer-elastic-rest" target="clean"/><ant dir="indexer-solr" target="clean"/><ant dir="language-identifier" target="clean"/><!-- <ant dir="lib-commons-httpclient" target="clean"/> -->diff --git a/src/plugin/indexer-elastic-rest/build-ivy.xml b/src/plugin/indexer-elastic-rest/build-ivy.xmlnew file mode 100644index 000000000..cac52c5ed--- /dev/null+++ b/src/plugin/indexer-elastic-rest/build-ivy.xml@@ -0,0 +1,54 @@+<?xml version="1.0"?>+<!--+ 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.+-->+<project name="indexer-elastic-rest" default="deps-jar" xmlns:ivy="antlib:org.apache.ivy.ant">++ <property name="ivy.install.version" value="2.1.0"/>+ <condition property="ivy.home" value="${env.IVY_HOME}">+ <isset property="env.IVY_HOME"/>+ </condition>+ <property name="ivy.home" value="${user.home}/.ant"/>+ <property name="ivy.checksums" value=""/>+ <property name="ivy.jar.dir" value="${ivy.home}/lib"/>+ <property name="ivy.jar.file" value="${ivy.jar.dir}/ivy.jar"/>++ <target name="download-ivy" unless="offline">++ <mkdir dir="${ivy.jar.dir}"/>+ <!-- download Ivy from web site so that it can be used even without any special installation -->+ <get src="http://repo2.maven.org/maven2/org/apache/ivy/ivy/${ivy.install.version}/ivy-${ivy.install.version}.jar"+ dest="${ivy.jar.file}" usetimestamp="true"/>+ </target>++ <target name="init-ivy" depends="download-ivy">+ <!-- try to load ivy here from ivy home, in case the user has not already dropped+ it into ant's lib dir (note that the latter copy will always take precedence).+ We will not fail as long as local lib dir exists (it may be empty) and+ ivy is in at least one of ant's lib dir or the local lib dir. -->+ <path id="ivy.lib.path">+ <fileset dir="${ivy.jar.dir}" includes="*.jar"/>++ </path>+ <taskdef resource="org/apache/ivy/ant/antlib.xml"+ uri="antlib:org.apache.ivy.ant" classpathref="ivy.lib.path"/>+ </target>++ <target name="deps-jar" depends="init-ivy">+ <ivy:retrieve pattern="lib/[artifact]-[revision].[ext]"/>+ </target>++</project>diff --git a/src/plugin/indexer-elastic-rest/build.xml b/src/plugin/indexer-elastic-rest/build.xmlnew file mode 100644index 000000000..95d2cd6ac--- /dev/null+++ b/src/plugin/indexer-elastic-rest/build.xml@@ -0,0 +1,22 @@+<?xml version="1.0"?>+<!--+ 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.+-->+<project name="indexer-elastic-rest" default="jar-core">++ <import file="../build-plugin.xml"/>++</project>diff --git a/src/plugin/indexer-elastic-rest/howto_upgrade_es.txt b/src/plugin/indexer-elastic-rest/howto_upgrade_es.txtnew file mode 100644index 000000000..b57705304--- /dev/null+++ b/src/plugin/indexer-elastic-rest/howto_upgrade_es.txt@@ -0,0 +1,6 @@+1. Upgrade elasticsearch dependency in src/plugin/indexer-elastic/ivy.xml++2. Upgrade the Elasticsearch specific dependencies in src/plugin/indexer-elastic/plugin.xml+ To get the list of dependencies and their versions execute:+ $ ant -f ./build-ivy.xml+ $ ls lib/diff --git a/src/plugin/indexer-elastic-rest/ivy.xml b/src/plugin/indexer-elastic-rest/ivy.xmlnew file mode 100644index 000000000..f834fd22c--- /dev/null+++ b/src/plugin/indexer-elastic-rest/ivy.xml@@ -0,0 +1,43 @@+<?xml version="1.0" ?>++<!--+ 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.+-->++<ivy-module version="1.0">+ <info organisation="org.apache.nutch" module="${ant.project.name}">+ <license name="Apache 2.0"/>+ <ivyauthor name="Apache Nutch Team" url="http://nutch.apache.org"/>+ <description>+ Apache Nutch+ </description>+ </info>++ <configurations>+ <include file="../../..//ivy/ivy-configurations.xml"/>+ </configurations>++ <publications>+ <!--get the artifact from our module name-->+ <artifact conf="master"/>+ </publications>++ <dependencies>+ <!-- https://mvnrepository.com/artifact/io.searchbox/jest -->+ <dependency org="io.searchbox" name="jest" rev="2.0.3" conf="*->default"/>+ </dependencies>++</ivy-module>diff --git a/src/plugin/indexer-elastic-rest/plugin.xml b/src/plugin/indexer-elastic-rest/plugin.xmlnew file mode 100644index 000000000..ee1adab3e--- /dev/null+++ b/src/plugin/indexer-elastic-rest/plugin.xml@@ -0,0 +1,52 @@+<?xml version="1.0" encoding="UTF-8"?>+<!--+ 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.+-->+<plugin id="indexer-elastic-rest" name="ElasticRestIndexWriter" version="1.0.0"+ provider-name="nutch.apache.org">++ <runtime>+ <library name="indexer-elastic-rest.jar">+ <export name="*"/>+ </library>++ <library name="commons-codec-1.9.jar"/>+ <library name="commons-lang3-3.4.jar"/>+ <library name="commons-logging-1.2.jar"/>+ <library name="gson-2.6.2.jar"/>+ <library name="guava-19.0.jar"/>+ <library name="httpasyncclient-4.1.1.jar"/>+ <library name="httpclient-4.5.2.jar"/>+ <library name="httpcore-4.4.4.jar"/>+ <library name="httpcore-nio-4.4.4.jar"/>+ <library name="jest-2.0.3.jar"/>+ <library name="jest-common-2.0.3.jar"/>+ <library name="slf4j-api-1.7.21.jar"/>++ </runtime>++ <requires>+ <import plugin="nutch-extensionpoints"/>+ </requires>++ <extension id="org.apache.nutch.indexer.elasticrest"+ name="Elasticsearch Rest Index Writer"+ point="org.apache.nutch.indexer.IndexWriter">+ <implementation id="ElasticRestIndexWriter"+ class="org.apache.nutch.indexwriter.elasticrest.ElasticRestIndexWriter"/>+ </extension>++</plugin>diff --git a/src/plugin/indexer-elastic-rest/src/java/org/apache/nutch/indexwriter/elasticrest/ElasticRestConstants.java b/src/plugin/indexer-elastic-rest/src/java/org/apache/nutch/indexwriter/elasticrest/ElasticRestConstants.javanew file mode 100644index 000000000..684cc03f8--- /dev/null+++ b/src/plugin/indexer-elastic-rest/src/java/org/apache/nutch/indexwriter/elasticrest/ElasticRestConstants.java@@ -0,0 +1,33 @@+/*+ * 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.nutch.indexwriter.elasticrest;++public interface ElasticRestConstants {+ public static final String ELASTIC_PREFIX = "elastic.rest.";++ public static final String HOST = ELASTIC_PREFIX + "host";+ public static final String PORT = ELASTIC_PREFIX + "port";+ public static final String INDEX = ELASTIC_PREFIX + "index";+ public static final String MAX_BULK_DOCS = ELASTIC_PREFIX + "max.bulk.docs";+ public static final String MAX_BULK_LENGTH = ELASTIC_PREFIX + "max.bulk.size";++ public static final String USER = ELASTIC_PREFIX + "user";+ public static final String PASSWORD = ELASTIC_PREFIX + "password";+ public static final String TYPE = ELASTIC_PREFIX + "type";+ public static final String HTTPS = ELASTIC_PREFIX + "https";+ public static final String HOSTNAME_TRUST = ELASTIC_PREFIX + "trustallhostnames";+}\ No newline at end of filediff --git a/src/plugin/indexer-elastic-rest/src/java/org/apache/nutch/indexwriter/elasticrest/ElasticRestIndexWriter.java b/src/plugin/indexer-elastic-rest/src/java/org/apache/nutch/indexwriter/elasticrest/ElasticRestIndexWriter.javanew file mode 100644index 000000000..639077e99--- /dev/null+++ b/src/plugin/indexer-elastic-rest/src/java/org/apache/nutch/indexwriter/elasticrest/ElasticRestIndexWriter.java@@ -0,0 +1,336 @@+/*+ * 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.+ */++//TODO trust self signed and non matching certs: http://stackoverflow.com/questions/2893819/telling-java-to-accept-self-signed-ssl-certificate+//TODO refactor the dependencies out of root ivy file++package org.apache.nutch.indexwriter.elasticrest;++import io.searchbox.client.JestClient;+import io.searchbox.client.JestClientFactory;+import io.searchbox.client.JestResult;+import io.searchbox.client.JestResultHandler;+import io.searchbox.client.config.HttpClientConfig;+import io.searchbox.core.Bulk;+import io.searchbox.core.BulkResult;+import io.searchbox.core.Delete;+import io.searchbox.core.Index;+import org.apache.commons.lang.StringUtils;+import org.apache.commons.lang3.exception.ExceptionUtils;+import org.apache.hadoop.conf.Configuration;+import org.apache.hadoop.mapred.JobConf;+import org.apache.http.HttpResponse;+import org.apache.http.concurrent.BasicFuture;+import org.apache.http.conn.ssl.DefaultHostnameVerifier;+import org.apache.http.conn.ssl.NoopHostnameVerifier;+import org.apache.http.conn.ssl.SSLConnectionSocketFactory;+import org.apache.http.nio.conn.SchemeIOSessionStrategy;+import org.apache.http.nio.conn.ssl.SSLIOSessionStrategy;+import org.apache.http.ssl.SSLContextBuilder;+import org.apache.http.ssl.TrustStrategy;+import org.apache.nutch.indexer.IndexWriter;+import org.apache.nutch.indexer.NutchDocument;+import org.slf4j.Logger;+import org.slf4j.LoggerFactory;++import javax.net.ssl.HostnameVerifier;+import javax.net.ssl.SSLContext;+import java.io.BufferedReader;+import java.io.IOException;+import java.net.URL;+import java.security.KeyManagementException;+import java.security.KeyStoreException;+import java.security.NoSuchAlgorithmException;+import java.security.cert.CertificateException;+import java.security.cert.X509Certificate;+import java.util.HashMap;+import java.util.Map;+import java.util.concurrent.ExecutionException;+import java.util.concurrent.Future;+++/**+ */+public class ElasticRestIndexWriter implements IndexWriter {+ public static Logger LOG = LoggerFactory.getLogger(ElasticRestIndexWriter.class);++ private static final int DEFAULT_MAX_BULK_DOCS = 250;+ private static final int DEFAULT_MAX_BULK_LENGTH = 2500500;++ private JestClient client;+ private String defaultIndex;+ private String defaultType = null;++ private Configuration config;++ private Bulk.Builder bulkBuilder;+ private Future<HttpResponse> execute;+ private int port = -1;+ private String host = null;+ private String user = null;+ private Boolean https = null;+ private String password = null;+ private Boolean trustAllHostnames = null;++ private int maxBulkDocs;+ private int maxBulkLength;+ private long indexedDocs = 0;+ private int bulkDocs = 0;+ private int bulkLength = 0;+ private boolean createNewBulk = false;+ private long millis;+ private BasicFuture<JestResult> basicFuture = null;++ @Override+ public void open(JobConf job, String name) throws IOException {++ host = job.get(ElasticRestConstants.HOST);+ port = job.getInt(ElasticRestConstants.PORT, 9200);+ user = job.get(ElasticRestConstants.USER);+ password = job.get(ElasticRestConstants.PASSWORD);+ https = job.getBoolean(ElasticRestConstants.HTTPS, false);+ trustAllHostnames = job.getBoolean(ElasticRestConstants.HOSTNAME_TRUST, false);++ // trust ALL certificates+ SSLContext sslContext = null;+ try {+ sslContext = new SSLContextBuilder().loadTrustMaterial(new TrustStrategy() {+ public boolean isTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {+ return true;+ }+ }).build();+ } catch (NoSuchAlgorithmException | KeyManagementException | KeyStoreException e) {+ e.printStackTrace();+ }++ // skip hostname checks+ HostnameVerifier hostnameVerifier = null;+ if (trustAllHostnames) {+ hostnameVerifier = new NoopHostnameVerifier();+ } else {+ hostnameVerifier = new DefaultHostnameVerifier();+ }++ SSLConnectionSocketFactory sslSocketFactory = new SSLConnectionSocketFactory(sslContext);+ SchemeIOSessionStrategy httpsIOSessionStrategy = new SSLIOSessionStrategy(sslContext, hostnameVerifier);++ JestClientFactory jestClientFactory = new JestClientFactory();+ URL urlOfElasticsearchNode = new URL(https ? "https" : "http", host, port, "");+++ if (host != null && port > 1) {+ HttpClientConfig.Builder builder = new HttpClientConfig.Builder(urlOfElasticsearchNode.toString())+ .multiThreaded(true)+ .connTimeout(300000)+ .readTimeout(300000);+ if (https) {+ if (user != null && password != null) {+ builder.defaultCredentials(user, password);+ }+ builder.defaultSchemeForDiscoveredNodes("https")+ .sslSocketFactory(sslSocketFactory) // this only affects sync calls+ .httpsIOSessionStrategy(httpsIOSessionStrategy); // this only affects async calls++ }+ jestClientFactory.setHttpClientConfig(builder.build());+ } else {+ throw new RuntimeException("No host and port specified");+ }++ client = jestClientFactory.getObject();++ defaultIndex = job.get(ElasticRestConstants.INDEX, "nutch");+ defaultType = job.get(ElasticRestConstants.TYPE, "doc");++ maxBulkDocs = job.getInt(ElasticRestConstants.MAX_BULK_DOCS,+ DEFAULT_MAX_BULK_DOCS);+ maxBulkLength = job.getInt(ElasticRestConstants.MAX_BULK_LENGTH,+ DEFAULT_MAX_BULK_LENGTH);++ bulkBuilder = new Bulk.Builder()+ .defaultIndex(defaultIndex)+ .defaultType(defaultType);++ }++ @Override+ public void write(NutchDocument doc) throws IOException {+ String id = (String) doc.getFieldValue("id");+ String type = doc.getDocumentMeta().get("type");+ if (type == null) {+ type = defaultType;+ }++ Map<String, Object> source = new HashMap<String, Object>();++ // Loop through all fields of this doc+ for (String fieldName : doc.getFieldNames()) {+ if (doc.getField(fieldName).getValues().size() > 1) {+ source.put(fieldName, doc.getFieldValue(fieldName));+ // Loop through the values to keep track of the size of this+ // document+ for (Object value : doc.getField(fieldName).getValues()) {+ bulkLength += value.toString().length();+ }+ } else {+ source.put(fieldName, doc.getFieldValue(fieldName));+ bulkLength += doc.getFieldValue(fieldName).toString().length();+ }+ }+ Index indexRequest = new Index.Builder(source)+ .index(defaultIndex)+ .type(type)+ .id(id)+ .build();++ // Add this indexing request to a bulk request+ bulkBuilder.addAction(indexRequest);++ indexedDocs++;+ bulkDocs++;++ if (bulkDocs >= maxBulkDocs || bulkLength >= maxBulkLength) {+ LOG.info("Processing bulk request [docs = " + bulkDocs + ", length = "+ + bulkLength + ", total docs = " + indexedDocs+ + ", last doc in bulk = '" + id + "']");+ // Flush the bulk of indexing requests+ createNewBulk = true;+ commit();+ }+ }++ @Override+ public void delete(String key) throws IOException {+ try {+ client.execute(new Delete.Builder(key)+ .index(defaultIndex)+ .type(defaultType)+ .build());+ } catch (IOException e) {+ LOG.error(ExceptionUtils.getStackTrace(e));+ throw e;+ }++ }++ @Override+ public void update(NutchDocument doc) throws IOException {+ try {+ write(doc);+ } catch (IOException e) {+ LOG.error(ExceptionUtils.getStackTrace(e));+ throw e;+ }+ }++ @Override+ public void commit() throws IOException {+ if (basicFuture != null) {+ // wait for previous to finish+ long beforeWait = System.currentTimeMillis();+ try {+ JestResult result = basicFuture.get();+ if (result == null) {+ throw new RuntimeException();+ }+ long msWaited = System.currentTimeMillis() - beforeWait;+ LOG.info("Previous took in ms " + millis+ + ", including wait " + msWaited);+ } catch (InterruptedException | ExecutionException e) {+ LOG.error("Error waiting for result ", e);+ }+ basicFuture = null;+ }+ if (bulkBuilder != null) {+ if (bulkDocs > 0) {+ // start a flush, note that this is an asynchronous call+ basicFuture = new BasicFuture<>(null);+ millis = System.currentTimeMillis();+ client.executeAsync(bulkBuilder.build(), new JestResultHandler<BulkResult>() {+ @Override+ public void completed(BulkResult bulkResult) {+ basicFuture.completed(bulkResult);+ millis = System.currentTimeMillis() - millis;+ }++ @Override+ public void failed(Exception e) {+ basicFuture.completed(null);+ LOG.error("Failed result: ", e);+ }+ });+ }+ bulkBuilder = null;+ }+ if (createNewBulk) {+ // Prepare a new bulk request+ bulkBuilder = new Bulk.Builder()+ .defaultIndex(defaultIndex)+ .defaultType(defaultType);+ bulkDocs = 0;+ bulkLength = 0;+ }+ }++ @Override+ public void close() throws IOException {+ // Flush pending requests+ LOG.info("Processing remaining requests [docs = " + bulkDocs+ + ", length = " + bulkLength + ", total docs = " + indexedDocs + "]");+ createNewBulk = false;+ commit();+ // flush one more time to finalize the last bulk+ LOG.info("Processing to finalize last execute");+ createNewBulk = false;+ commit();++ // Close+ client.shutdownClient();+ }++ @Override+ public String describe() {+ StringBuffer sb = new StringBuffer("ElasticRestIndexWriter\n");+ sb.append("\t").append(ElasticRestConstants.HOST).append(" : hostname\n");+ sb.append("\t").append(ElasticRestConstants.PORT).append(" : port\n");+ sb.append("\t").append(ElasticRestConstants.INDEX)+ .append(" : elastic index command \n");+ sb.append("\t").append(ElasticRestConstants.MAX_BULK_DOCS)+ .append(" : elastic bulk index doc counts. (default 250) \n");+ sb.append("\t").append(ElasticRestConstants.MAX_BULK_LENGTH)+ .append(" : elastic bulk index length. (default 2500500 ~2.5MB)\n");+ return sb.toString();+ }++ @Override+ public void setConf(Configuration conf) {+ config = conf;+ String host = conf.get(ElasticRestConstants.HOST);++ if (StringUtils.isBlank(host)) {+ String message = "Missing elastic.host. It should be set in nutch-site.xml ";+ message += "\n" + describe();+ LOG.error(message);+ throw new RuntimeException(message);+ }+ }++ @Override+ public Configuration getConf() {+ return config;+ }+}\ No newline at end of filediff --git a/src/plugin/indexer-elastic-rest/src/java/org/apache/nutch/indexwriter/elasticrest/package-info.java b/src/plugin/indexer-elastic-rest/src/java/org/apache/nutch/indexwriter/elasticrest/package-info.javanew file mode 100644index 000000000..fc1445116--- /dev/null+++ b/src/plugin/indexer-elastic-rest/src/java/org/apache/nutch/indexwriter/elasticrest/package-info.java@@ -0,0 +1,22 @@+/*+ * 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.+ */++/**+ * Index writer plugin for <a href="http://www.elasticsearch.org/">Elasticsearch</a>.+ */+package org.apache.nutch.indexwriter.elasticrest;+