Apache Nutch is an extensible and scalable web crawler
store structured_data as an array of objects
Nicola Marcacci Rossi160758023e3d
diff --git a/src/plugin/any23/src/java/org/apache/nutch/any23/Any23IndexingFilter.java b/src/plugin/any23/src/java/org/apache/nutch/any23/Any23IndexingFilter.javaindex 4b63f2082..1acda9306 100644--- a/src/plugin/any23/src/java/org/apache/nutch/any23/Any23IndexingFilter.java+++ b/src/plugin/any23/src/java/org/apache/nutch/any23/Any23IndexingFilter.java@@ -16,6 +16,11 @@*/package org.apache.nutch.any23;+import java.util.HashMap;+import java.util.Map;+import java.util.regex.Matcher;+import java.util.regex.Pattern;+import org.apache.hadoop.conf.Configuration;import org.apache.hadoop.io.Text;import org.apache.nutch.crawl.CrawlDatum;@@ -24,6 +29,8 @@ import org.apache.nutch.indexer.IndexingException;import org.apache.nutch.indexer.IndexingFilter;import org.apache.nutch.indexer.NutchDocument;import org.apache.nutch.parse.Parse;+import org.slf4j.Logger;+import org.slf4j.LoggerFactory;/*** <p>This implementation of {@link org.apache.nutch.indexer.IndexingFilter}@@ -33,6 +40,11 @@ import org.apache.nutch.parse.Parse;*/public class Any23IndexingFilter implements IndexingFilter {+ /** Logging instance */+ public static final Logger LOG = LoggerFactory.getLogger(Any23IndexingFilter.class);++ public static final String STRUCTURED_DATA = "structured_data";+private Configuration conf;/**@@ -73,15 +85,33 @@ public class Any23IndexingFilter implements IndexingFilter {*/@Overridepublic NutchDocument filter(NutchDocument doc, Parse parse, Text url, CrawlDatum datum, Inlinks inlinks) throws IndexingException {- // Check if some Triples are found, possibly put there by Any23ParseFilterString[] metadata = parse.getData().getParseMeta().getValues(Any23ParseFilter.ANY23_TRIPLES);- if (metadata != null && metadata.length >= 1) {- String[] triples = metadata[0].split("\t");- for (String triple : triples) {- doc.add("triple", triple);+ if (metadata != null) {+ for (String triple : metadata) {+ Pattern pattern = Pattern.compile("^([^ ]+) ([^ ]+) (.+) \\.");+ Matcher matcher = pattern.matcher(triple);+ if (matcher.find()) {+ Map<String, String> map = new HashMap<>();+ map.put("node", matcher.group(1));+ map.put("key", matcher.group(2));+ map.put("short_key", keyToShortKey(matcher.group(2)));+ map.put("value", matcher.group(3));+ doc.add("structured_data", map);+ } else {+ LOG.warn("Unsupported triple format " + triple);+ }}}return doc;}++ private String keyToShortKey(String key) {+ if (key.startsWith("<") && key.endsWith(">")) {+ key = key.substring(1, key.length() - 1);+ }+ String[] keyParts = key.split("/");+ String[] keySubParts = keyParts[keyParts.length - 1].split("#");+ return keySubParts[keySubParts.length - 1];+ }}diff --git a/src/plugin/any23/src/java/org/apache/nutch/any23/Any23ParseFilter.java b/src/plugin/any23/src/java/org/apache/nutch/any23/Any23ParseFilter.javaindex d47cbdda0..e9b7b3bdb 100644--- a/src/plugin/any23/src/java/org/apache/nutch/any23/Any23ParseFilter.java+++ b/src/plugin/any23/src/java/org/apache/nutch/any23/Any23ParseFilter.java@@ -103,7 +103,6 @@ public class Any23ParseFilter implements HtmlParseFilter {any23.setMIMETypeDetector(null);try {-// Fix input to avoid extraction error (https://github.com/semarglproject/semargl/issues/37#issuecomment-69381281)XMLReader reader = SAXParserImpl.newInstance(null).getXMLReader();ByteArrayOutputStream baos = new ByteArrayOutputStream();@@ -162,17 +161,13 @@ public class Any23ParseFilter implements HtmlParseFilter {throw new RuntimeException("Error running Any23 parser: " + e.getMessage());}Set<String> triples = parser.getTriples();- // can't store multiple values in page metadata -> separate by tabs- StringBuilder sb = new StringBuilder();Parse parse = parseResult.get(content.getUrl());Metadata metadata = parse.getData().getParseMeta();for (String triple : triples) {- sb.append(triple);- sb.append("\t");+ metadata.add(ANY23_TRIPLES, triple);}- metadata.add(ANY23_TRIPLES, sb.toString());return parseResult;}diff --git a/src/plugin/any23/src/test/org/apache/nutch/any23/TestAny23IndexingFilter.java b/src/plugin/any23/src/test/org/apache/nutch/any23/TestAny23IndexingFilter.javaindex 7346e4c70..0f98e28be 100644--- a/src/plugin/any23/src/test/org/apache/nutch/any23/TestAny23IndexingFilter.java+++ b/src/plugin/any23/src/test/org/apache/nutch/any23/TestAny23IndexingFilter.java@@ -18,18 +18,24 @@ package org.apache.nutch.any23;import static org.junit.Assert.*;-import java.nio.ByteBuffer;+import java.util.List;+import java.util.Map;-import org.apache.avro.util.Utf8;+import org.apache.hadoop.io.Text;import org.apache.hadoop.conf.Configuration;+import org.apache.nutch.crawl.CrawlDatum;+import org.apache.nutch.crawl.Inlinks;import org.apache.nutch.indexer.NutchDocument;-import org.apache.nutch.storage.WebPage;+import org.apache.nutch.metadata.Metadata;+import org.apache.nutch.parse.Outlink;+import org.apache.nutch.parse.ParseData;+import org.apache.nutch.parse.ParseImpl;+import org.apache.nutch.parse.ParseStatus;import org.apache.nutch.util.NutchConfiguration;import org.junit.Assert;import org.junit.Test;public class TestAny23IndexingFilter {-@Testpublic void testAny23TriplesFields() throws Exception {Configuration conf = NutchConfiguration.create();@@ -37,18 +43,41 @@ public class TestAny23IndexingFilter {filter.setConf(conf);Assert.assertNotNull(filter);NutchDocument doc = new NutchDocument();- WebPage page = new WebPage();- byte[] bytes = new byte[10];- ByteBuffer bbuf = ByteBuffer.wrap(bytes);- page.putToMetadata(new Utf8(Any23ParseFilter.ANY23_TRIPLES), bbuf);+ ParseData parseData = new ParseData(ParseStatus.STATUS_SUCCESS, "The Foo Page",+ new Outlink[] { }, new Metadata());+ ParseImpl parse = new ParseImpl("test page", parseData);+ String[] triples = new String[]{+ "<http://dbpedia.org/resource/Z\u00FCrich> <http://www.w3.org/2002/07/owl#sameAs> <http://rdf.freebase.com/ns/m.08966> .",+ "<http://dbpedia.org/resource/Z\u00FCrich> <http://dbpedia.org/property/yearHumidity> \"77\" .",+ "<http://dbpedia.org/resource/Z\u00FCrich> <http://www.w3.org/2000/01/rdf-schema#label> \"Zurique\"@pt ."+ };+ for (String triple : triples) {+ parse.getData().getParseMeta().add(Any23ParseFilter.ANY23_TRIPLES, triple);+ }try {- filter.filter(doc, "http://nutch.apache.org/", page);+ doc = filter.filter(doc, parse, new Text("http://nutch.apache.org/"), new CrawlDatum(), new Inlinks());} catch (Exception e) {e.printStackTrace();fail(e.getMessage());}- Assert.assertNotNull(doc);- Assert.assertTrue("check for 'triple' field", doc.getFieldNames().contains("triple"));- }+ List<Object> docTriples = doc.getField(Any23IndexingFilter.STRUCTURED_DATA).getValues();+ Assert.assertEquals(docTriples.size(), triples.length);+ Object triple = docTriples.get(0);+ Assert.assertTrue(triple instanceof Map<?, ?>);+ @SuppressWarnings("unchecked")+ Map<String, String> structuredData = (Map<String, String>) triple;+ Assert.assertEquals(structuredData.get("node"), "<http://dbpedia.org/resource/Z\u00FCrich>");+ Assert.assertEquals(structuredData.get("key"), "<http://www.w3.org/2002/07/owl#sameAs>");+ Assert.assertEquals(structuredData.get("short_key"), "sameAs");+ Assert.assertEquals(structuredData.get("value"), "<http://rdf.freebase.com/ns/m.08966>");++ triple = docTriples.get(1);+ Assert.assertTrue(triple instanceof Map<?, ?>);+ structuredData = (Map<String, String>) triple;+ Assert.assertEquals(structuredData.get("node"), "<http://dbpedia.org/resource/Z\u00FCrich>");+ Assert.assertEquals(structuredData.get("key"), "<http://dbpedia.org/property/yearHumidity>");+ Assert.assertEquals(structuredData.get("short_key"), "yearHumidity");+ Assert.assertEquals(structuredData.get("value"), "\"77\"");+ }}diff --git a/src/plugin/any23/src/test/org/apache/nutch/any23/TestAny23ParseFilter.java b/src/plugin/any23/src/test/org/apache/nutch/any23/TestAny23ParseFilter.javaindex 99a09d374..dfc092862 100644--- a/src/plugin/any23/src/test/org/apache/nutch/any23/TestAny23ParseFilter.java+++ b/src/plugin/any23/src/test/org/apache/nutch/any23/TestAny23ParseFilter.java@@ -21,14 +21,25 @@ import java.io.File;import java.io.FileInputStream;import java.io.IOException;import java.nio.ByteBuffer;+import java.util.Arrays;import org.apache.avro.util.Utf8;import org.apache.hadoop.conf.Configuration;+import org.apache.hadoop.io.Text;+import org.apache.nutch.crawl.CrawlDatum;+import org.apache.nutch.indexer.NutchDocument;+import org.apache.nutch.metadata.Metadata;+import org.apache.nutch.parse.Outlink;import org.apache.nutch.parse.Parse;+import org.apache.nutch.parse.ParseData;import org.apache.nutch.parse.ParseException;+import org.apache.nutch.parse.ParseImpl;+import org.apache.nutch.parse.ParseStatus;import org.apache.nutch.parse.ParseUtil;import org.apache.nutch.parse.ParserNotFound;-import org.apache.nutch.storage.WebPage;+import org.apache.nutch.protocol.Content;+import org.apache.nutch.protocol.Protocol;+import org.apache.nutch.protocol.ProtocolFactory;import org.apache.nutch.util.MimeUtil;import org.apache.nutch.util.NutchConfiguration;import org.junit.Assert;@@ -51,15 +62,16 @@ public class TestAny23ParseFilter {private String file2 = "microdata_basic.html";- private static final int EXPECTED_TRIPLES_1 = 117;+ private static final int EXPECTED_TRIPLES_1 = 79;- private static final int EXPECTED_TRIPLES_2 = 40;+ private static final int EXPECTED_TRIPLES_2 = 39;@Beforepublic void setUp() {this.conf = NutchConfiguration.create();conf.set("file.content.limit", "-1");conf.set("parser.timeout", "-1");+ conf.set(Any23ParseFilter.ANY_23_EXTRACTORS_CONF, "html-embedded-jsonld,html-head-icbm,html-head-links,html-head-meta,html-head-title,html-mf-adr,html-mf-geo,html-mf-hcalendar,html-mf-hcard,html-mf-hlisting,html-mf-hrecipe,html-mf-hresume,html-mf-hreview,html-mf-hreview-aggregate,html-mf-license,html-mf-species,html-mf-xfn,html-microdata,html-rdfa11,html-xpath");}@Test@@ -87,27 +99,18 @@ public class TestAny23ParseFilter {EXPECTED_TRIPLES_2, triplesArray.length);}- public String[] extract(String urlString, File file) throws IOException, ParserNotFound, ParseException {- @SuppressWarnings("unused")- Parse parse;- byte[] bytes = new byte[(int) file.length()];- DataInputStream in = new DataInputStream(new FileInputStream(file));- in.readFully(bytes);- in.close();-- WebPage page = new WebPage();- page.setBaseUrl(new Utf8(urlString));- page.setContent(ByteBuffer.wrap(bytes));- MimeUtil mimeutil = new MimeUtil(conf);- String mtype = mimeutil.getMimeType(file);- page.setContentType(new Utf8(mtype));- parse = new ParseUtil(conf).parse(urlString, page);- ByteBuffer bbuf = page.getFromMetadata(new Utf8("Any23-Triples"));- byte[] byteArray = new byte[bbuf.remaining()];- bbuf.get(byteArray);- String s = new String(byteArray);- String[] triplesArray = s.split("\t");-- return triplesArray;+ public String[] extract(String urlString, File file) {+ try {+ System.out.println(urlString);+ Protocol protocol = new ProtocolFactory(conf).getProtocol(urlString);+ Content content = protocol.getProtocolOutput(new Text(urlString),+ new CrawlDatum()).getContent();+ Parse parse = new ParseUtil(conf).parse(content).get(content.getUrl());+ return parse.getData().getParseMeta().getValues(Any23ParseFilter.ANY23_TRIPLES);+ } catch (Exception e) {+ e.printStackTrace();+ Assert.fail(e.toString());+ }+ return null;}}diff --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.javaindex 5e71b3c5d..6371362e9 100644--- 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.java@@ -57,6 +57,7 @@ import java.security.cert.X509Certificate;import java.util.HashMap;import java.util.Map;import java.util.HashSet;+import java.util.List;import java.util.Set;import java.util.concurrent.ExecutionException;@@ -168,6 +169,18 @@ public class ElasticRestIndexWriter implements IndexWriter {bulkBuilder = new Bulk.Builder().defaultIndex(defaultIndex).defaultType(defaultType);}++ private static Object normalizeValue(Object value) {+ if (value == null) {+ return null;+ }++ if (value instanceof Map) {+ return value;+ }++ return value.toString();+ }@Overridepublic void write(NutchDocument doc) throws IOException {@@ -181,22 +194,19 @@ public class ElasticRestIndexWriter implements IndexWriter {// Loop through all fields of this docfor (String fieldName : doc.getFieldNames()) {- Set<String> allFieldValues = new HashSet<String>();- for (Object value : doc.getField(fieldName).getValues()) {- allFieldValues.add(value.toString());- }- String[] fieldValues = allFieldValues.toArray(new String[allFieldValues.size()]);- if (fieldValues.length > 1) {+ List<Object> fieldValues = doc.getField(fieldName).getValues();++ if (fieldValues.size() > 1) {// Loop through the values to keep track of the size of this// document- for (String value : fieldValues) {- bulkLength += value.length();+ for (Object value : fieldValues) {+ bulkLength += value.toString().length();}- source.put(fieldName, fieldValues);- } else if(fieldValues.length == 1) {- source.put(fieldName, fieldValues[0]);- bulkLength += fieldValues[0].length();+ source.put(fieldName, fieldValues.stream().map(ElasticRestIndexWriter::normalizeValue).toArray());+ } else if(fieldValues.size() == 1) {+ source.put(fieldName, fieldValues.get(0));+ bulkLength += fieldValues.get(0).toString().length();}}