Skip to content

armgit / nutch

Public Imported from GitHub
0

Apache Nutch is an extensible and scalable web crawler

NUTCH-646: New Indexing Framework for Nutch.

Dennis Kubesdd0563795271
diff --git a/src/java/org/apache/nutch/indexer/field/AnchorFields.java b/src/java/org/apache/nutch/indexer/field/AnchorFields.java
new file mode 100644
index 000000000..bbaf9478a
--- /dev/null
+++ b/src/java/org/apache/nutch/indexer/field/AnchorFields.java
@@ -0,0 +1,405 @@
+package org.apache.nutch.indexer.field;
+
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.Comparator;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Random;
+
+import org.apache.commons.cli.CommandLine;
+import org.apache.commons.cli.CommandLineParser;
+import org.apache.commons.cli.GnuParser;
+import org.apache.commons.cli.HelpFormatter;
+import org.apache.commons.cli.Option;
+import org.apache.commons.cli.OptionBuilder;
+import org.apache.commons.cli.Options;
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.apache.hadoop.conf.Configuration;
+import org.apache.hadoop.conf.Configured;
+import org.apache.hadoop.fs.FileSystem;
+import org.apache.hadoop.fs.Path;
+import org.apache.hadoop.io.ObjectWritable;
+import org.apache.hadoop.io.Text;
+import org.apache.hadoop.io.Writable;
+import org.apache.hadoop.mapred.FileInputFormat;
+import org.apache.hadoop.mapred.FileOutputFormat;
+import org.apache.hadoop.mapred.JobClient;
+import org.apache.hadoop.mapred.JobConf;
+import org.apache.hadoop.mapred.Mapper;
+import org.apache.hadoop.mapred.OutputCollector;
+import org.apache.hadoop.mapred.Reducer;
+import org.apache.hadoop.mapred.Reporter;
+import org.apache.hadoop.mapred.SequenceFileInputFormat;
+import org.apache.hadoop.mapred.SequenceFileOutputFormat;
+import org.apache.hadoop.util.StringUtils;
+import org.apache.hadoop.util.Tool;
+import org.apache.hadoop.util.ToolRunner;
+import org.apache.nutch.scoring.webgraph.LinkDatum;
+import org.apache.nutch.scoring.webgraph.Node;
+import org.apache.nutch.scoring.webgraph.WebGraph;
+import org.apache.nutch.util.NutchConfiguration;
+import org.apache.nutch.util.NutchJob;
+
+/**
+ * Creates FieldWritable objects for inbound anchor text. These FieldWritable
+ * objects are then included in the input to the FieldIndexer to be converted
+ * to Lucene Field objects and indexed.
+ *
+ * Any empty or null anchor text is ignored. Anchors are sorted in descending
+ * order according to the score of their parent pages. There are settings for a
+ * maximum number of anchors to index and whether those anchors should be stored
+ * and tokenized. With a descending order by score and a maximum anchors index
+ * we ensure that only the best anchors are indexed assuming that a higher link
+ * analysis score equals a better page and better inbound text.
+ */
+public class AnchorFields
+ extends Configured
+ implements Tool {
+
+ public static final Log LOG = LogFactory.getLog(AnchorFields.class);
+
+ /**
+ * Comparator to order the links in descending order by score.
+ */
+ private static class DescendinLinkDatumScoreComparator
+ implements Comparator<LinkDatum> {
+
+ public int compare(LinkDatum one, LinkDatum two) {
+ float scoreOne = one.getScore();
+ float scoreTwo = two.getScore();
+ return (scoreOne == scoreTwo ? 0 : (scoreOne > scoreTwo ? -1 : 1));
+ }
+ }
+
+ /**
+ * Runs the Extractor job. Get outlinks to be converted while ignoring empty
+ * and null anchors.
+ *
+ * @param webGraphDb The WebGraphDb to pull from.
+ * @param output The extractor output.
+ *
+ * @throws IOException If an error occurs while running the extractor.
+ */
+ private void runExtractor(Path webGraphDb, Path output)
+ throws IOException {
+
+ JobConf extractor = new NutchJob(getConf());
+ extractor.setJobName("AnchorFields Extractor");
+ FileInputFormat.addInputPath(extractor, new Path(webGraphDb,
+ WebGraph.OUTLINK_DIR));
+ FileInputFormat.addInputPath(extractor, new Path(webGraphDb,
+ WebGraph.NODE_DIR));
+ FileOutputFormat.setOutputPath(extractor, output);
+ extractor.setInputFormat(SequenceFileInputFormat.class);
+ extractor.setMapperClass(Extractor.class);
+ extractor.setReducerClass(Extractor.class);
+ extractor.setMapOutputKeyClass(Text.class);
+ extractor.setMapOutputValueClass(ObjectWritable.class);
+ extractor.setOutputKeyClass(Text.class);
+ extractor.setOutputValueClass(LinkDatum.class);
+ extractor.setOutputFormat(SequenceFileOutputFormat.class);
+
+ LOG.info("Starting extractor job");
+ try {
+ JobClient.runJob(extractor);
+ }
+ catch (IOException e) {
+ LOG.error(StringUtils.stringifyException(e));
+ throw e;
+ }
+ LOG.info("Finished extractor job.");
+ }
+
+ /**
+ * Runs the collector job. Aggregates extracted inlinks, sorts and converts
+ * the highest scoring into FieldWritable objects. Only inlinks for which
+ * basic fields exist will be collected to avoid orphan fields.
+ *
+ * @param basicFields The BasicFields which must be present to collect anchors
+ * to avoid orphan fields.
+ * @param links The outlinks path.
+ * @param output The collector output.
+ *
+ * @throws IOException If an error occurs while running the collector.
+ */
+ private void runCollector(Path basicFields, Path links, Path output)
+ throws IOException {
+
+ JobConf collector = new NutchJob(getConf());
+ collector.setJobName("AnchorFields Collector");
+ FileInputFormat.addInputPath(collector, links);
+ FileInputFormat.addInputPath(collector, basicFields);
+ FileOutputFormat.setOutputPath(collector, output);
+ collector.setInputFormat(SequenceFileInputFormat.class);
+ collector.setMapOutputKeyClass(Text.class);
+ collector.setMapOutputValueClass(ObjectWritable.class);
+ collector.setMapperClass(Collector.class);
+ collector.setReducerClass(Collector.class);
+ collector.setOutputKeyClass(Text.class);
+ collector.setOutputValueClass(FieldWritable.class);
+ collector.setOutputFormat(SequenceFileOutputFormat.class);
+
+ LOG.info("Starting collector job");
+ try {
+ JobClient.runJob(collector);
+ }
+ catch (IOException e) {
+ LOG.error(StringUtils.stringifyException(e));
+ throw e;
+ }
+ LOG.info("Finished collector job.");
+ }
+
+ /**
+ * Extracts outlinks to be created as FieldWritable objects. Ignores empty
+ * and null anchors.
+ */
+ public static class Extractor
+ extends Configured
+ implements Mapper<Text, Writable, Text, ObjectWritable>,
+ Reducer<Text, ObjectWritable, Text, LinkDatum> {
+
+ private boolean ignoreEmptyAnchors = true;
+ private JobConf conf;
+
+ /**
+ * Default constructor.
+ */
+ public Extractor() {
+ }
+
+ /**
+ * Configurable constructor.
+ */
+ public Extractor(Configuration conf) {
+ setConf(conf);
+ }
+
+ /**
+ * Configures the job, sets to ignore empty anchors.
+ */
+ public void configure(JobConf conf) {
+ this.conf = conf;
+ ignoreEmptyAnchors = conf.getBoolean("link.ignore.empty.anchors", true);
+ }
+
+ /**
+ * Wraps values in ObjectWritable
+ */
+ public void map(Text key, Writable value,
+ OutputCollector<Text, ObjectWritable> output, Reporter reporter)
+ throws IOException {
+
+ ObjectWritable objWrite = new ObjectWritable();
+ objWrite.set(value);
+ output.collect(key, objWrite);
+ }
+
+ /**
+ * Extracts and inverts outlinks, ignores empty anchors.
+ */
+ public void reduce(Text key, Iterator<ObjectWritable> values,
+ OutputCollector<Text, LinkDatum> output, Reporter reporter)
+ throws IOException {
+
+ List<LinkDatum> outlinkList = new ArrayList<LinkDatum>();
+ Node node = null;
+
+ // collect the outlinks while ignoring links with empty anchor text, also
+ // assign the node
+ while (values.hasNext()) {
+ ObjectWritable objWrite = values.next();
+ Object obj = objWrite.get();
+ if (obj instanceof LinkDatum) {
+ LinkDatum next = (LinkDatum)obj;
+ String anchor = next.getAnchor();
+ if (anchor != null) {
+ anchor = anchor.trim();
+ }
+ if (ignoreEmptyAnchors && (anchor == null || anchor.length() == 0)) {
+ continue;
+ }
+ outlinkList.add(next);
+ }
+ else if (obj instanceof Node) {
+ node = (Node)obj;
+ }
+ }
+
+ // has to have outlinks to index
+ if (node != null && outlinkList.size() > 0) {
+ String fromUrl = key.toString();
+ float outlinkScore = node.getInlinkScore();
+ for (LinkDatum datum : outlinkList) {
+ String toUrl = datum.getUrl();
+ datum.setUrl(fromUrl);
+ datum.setScore(outlinkScore);
+ datum.setLinkType(LinkDatum.INLINK);
+ output.collect(new Text(toUrl), datum);
+ }
+ }
+ }
+
+ public void close() {
+ }
+ }
+
+ /**
+ * Collects and creates FieldWritable objects from the inlinks. Inlinks are
+ * first sorted by descending score before being collected.
+ */
+ public static class Collector
+ extends Configured
+ implements Mapper<Text, Writable, Text, ObjectWritable>,
+ Reducer<Text, ObjectWritable, Text, FieldWritable> {
+
+ private int maxInlinks = 1000;
+ private boolean tokenize = true;
+ private boolean stored = false;
+ private Comparator<LinkDatum> descLinkComp = new DescendinLinkDatumScoreComparator();
+
+ /**
+ * Configures the jobs. Sets maximum number of inlinks and whether to
+ * tokenize and store.
+ */
+ public void configure(JobConf conf) {
+ this.maxInlinks = conf.getInt("link.max.inlinks", 1000);
+ this.tokenize = conf.getBoolean("indexer.anchor.tokenize", true);
+ this.stored = conf.getBoolean("indexer.anchor.stored", false);
+ }
+
+ public void close() {
+ }
+
+ /**
+ * Wraps values in ObjectWritable
+ */
+ public void map(Text key, Writable value,
+ OutputCollector<Text, ObjectWritable> output, Reporter reporter)
+ throws IOException {
+
+ ObjectWritable objWrite = new ObjectWritable();
+ objWrite.set(value);
+ output.collect(key, objWrite);
+ }
+
+ /**
+ * Aggregates and sorts inlinks. Then converts up to a max number to
+ * FieldWritable objects.
+ */
+ public void reduce(Text key, Iterator<ObjectWritable> values,
+ OutputCollector<Text, FieldWritable> output, Reporter reporter)
+ throws IOException {
+
+ List<LinkDatum> anchors = new ArrayList<LinkDatum>();
+ FieldsWritable basicFields = null;
+
+ // aggregate inlinks assign basic fields
+ while (values.hasNext()) {
+ ObjectWritable objWrite = values.next();
+ Object obj = objWrite.get();
+ if (obj instanceof LinkDatum) {
+ anchors.add((LinkDatum)obj);
+ }
+ else if (obj instanceof FieldsWritable) {
+ basicFields = (FieldsWritable)obj;
+ }
+ }
+
+ // only collect anchors for those urls that have basic fields, otherwise
+ // we get orphan entries indexed only under anchor text
+ if (basicFields != null && anchors.size() > 0) {
+
+ // sort according to score descending
+ Collections.sort(anchors, descLinkComp);
+
+ // collect to maximum number of inlinks
+ int numToCollect = (maxInlinks > anchors.size() ? anchors.size()
+ : maxInlinks);
+ for (int i = 0; i < numToCollect; i++) {
+ LinkDatum datum = anchors.get(i);
+ FieldWritable anchorField = new FieldWritable(Fields.ANCHOR,
+ datum.getAnchor(), FieldType.CONTENT, true, stored, tokenize);
+ output.collect(key, anchorField);
+ }
+ }
+ }
+ }
+
+ /**
+ * Creates the FieldsWritable object from the anchors.
+ *
+ * @param webGraphDb The WebGraph from which to pull outlinks.
+ * @param basicFields The BasicFields that must be present to avoid orphan
+ * anchor fields.
+ * @param output The AnchorFields output.
+ *
+ * @throws IOException If an error occurs while creating the fields.
+ */
+ public void createFields(Path webGraphDb, Path basicFields, Path output)
+ throws IOException {
+
+ Configuration conf = getConf();
+ FileSystem fs = FileSystem.get(conf);
+ Path tempLinks = new Path(output + "-"
+ + Integer.toString(new Random().nextInt(Integer.MAX_VALUE)));
+ runExtractor(webGraphDb, tempLinks);
+ runCollector(basicFields, tempLinks, output);
+ fs.delete(tempLinks, true);
+ }
+
+ public static void main(String[] args)
+ throws Exception {
+ int res = ToolRunner.run(NutchConfiguration.create(), new AnchorFields(),
+ args);
+ System.exit(res);
+ }
+
+ /**
+ * Runs the AnchorFields job.
+ */
+ public int run(String[] args)
+ throws Exception {
+
+ Options options = new Options();
+ Option helpOpts = OptionBuilder.withArgName("help").withDescription(
+ "show this help message").create("help");
+ Option outputOpts = OptionBuilder.withArgName("output").hasArg().withDescription(
+ "the output index directory").create("output");
+ Option webGraphDbOpts = OptionBuilder.withArgName("webgraphdb").hasArg().withDescription(
+ "the webgraphdb to use").create("webgraphdb");
+ Option basicFieldOpts = OptionBuilder.withArgName("basicfields").hasArgs().withDescription(
+ "the basicfields to use").create("basicfields");
+ options.addOption(helpOpts);
+ options.addOption(webGraphDbOpts);
+ options.addOption(basicFieldOpts);
+ options.addOption(outputOpts);
+
+ CommandLineParser parser = new GnuParser();
+ try {
+
+ CommandLine line = parser.parse(options, args);
+ if (line.hasOption("help") || !line.hasOption("webgraphdb")
+ || !line.hasOption("output") || !line.hasOption("basicfields")) {
+ HelpFormatter formatter = new HelpFormatter();
+ formatter.printHelp("AnchorFields", options);
+ return -1;
+ }
+
+ String webGraphDb = line.getOptionValue("webgraphdb");
+ String output = line.getOptionValue("output");
+ String basicFields = line.getOptionValue("basicfields");
+
+ createFields(new Path(webGraphDb), new Path(basicFields),
+ new Path(output));
+ return 0;
+ }
+ catch (Exception e) {
+ LOG.fatal("AnchorFields: " + StringUtils.stringifyException(e));
+ return -2;
+ }
+ }
+}
diff --git a/src/java/org/apache/nutch/indexer/field/BasicFields.java b/src/java/org/apache/nutch/indexer/field/BasicFields.java
new file mode 100644
index 000000000..40b639e0a
--- /dev/null
+++ b/src/java/org/apache/nutch/indexer/field/BasicFields.java
@@ -0,0 +1,765 @@
+package org.apache.nutch.indexer.field;
+
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Random;
+
+import org.apache.commons.cli.CommandLine;
+import org.apache.commons.cli.CommandLineParser;
+import org.apache.commons.cli.GnuParser;
+import org.apache.commons.cli.HelpFormatter;
+import org.apache.commons.cli.Option;
+import org.apache.commons.cli.OptionBuilder;
+import org.apache.commons.cli.Options;
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.apache.hadoop.conf.Configuration;
+import org.apache.hadoop.conf.Configured;
+import org.apache.hadoop.fs.FileSystem;
+import org.apache.hadoop.fs.Path;
+import org.apache.hadoop.io.ObjectWritable;
+import org.apache.hadoop.io.Text;
+import org.apache.hadoop.io.Writable;
+import org.apache.hadoop.io.WritableUtils;
+import org.apache.hadoop.mapred.FileInputFormat;
+import org.apache.hadoop.mapred.FileOutputFormat;
+import org.apache.hadoop.mapred.JobClient;
+import org.apache.hadoop.mapred.JobConf;
+import org.apache.hadoop.mapred.Mapper;
+import org.apache.hadoop.mapred.OutputCollector;
+import org.apache.hadoop.mapred.Reducer;
+import org.apache.hadoop.mapred.Reporter;
+import org.apache.hadoop.mapred.SequenceFileInputFormat;
+import org.apache.hadoop.mapred.SequenceFileOutputFormat;
+import org.apache.hadoop.util.StringUtils;
+import org.apache.hadoop.util.Tool;
+import org.apache.hadoop.util.ToolRunner;
+import org.apache.lucene.document.DateTools;
+import org.apache.nutch.crawl.CrawlDatum;
+import org.apache.nutch.metadata.Metadata;
+import org.apache.nutch.metadata.Nutch;
+import org.apache.nutch.parse.Parse;
+import org.apache.nutch.parse.ParseData;
+import org.apache.nutch.parse.ParseImpl;
+import org.apache.nutch.parse.ParseText;
+import org.apache.nutch.scoring.webgraph.LinkDatum;
+import org.apache.nutch.scoring.webgraph.Node;
+import org.apache.nutch.scoring.webgraph.WebGraph;
+import org.apache.nutch.util.NutchConfiguration;
+import org.apache.nutch.util.NutchJob;
+import org.apache.nutch.util.URLUtil;
+
+/**
+ * Creates the basic FieldWritable objects. The basic fields are the main
+ * fields used in indexing segments. Many other fields jobs will rely on the
+ * urls being present in the basic fields output to create their fields for
+ * indexing.
+ *
+ * Basic fields are extracted from segements. Only urls that were successfully
+ * fetched and parsed will be converted. This job also implements a portion of
+ * redirect logic. If a url contains both a redirect or orig url then both the
+ * url and its orig will be measured against their link analysis score with the
+ * highest scoring one being the url used for display in the index. This
+ * ensures that we index content under the best, most popular, url which is most
+ * often the one users are expecting.
+ *
+ * The BasicFields tool can accept one or more segments to convert to fields.
+ * If multiple segments have overlapping content, only the latest successfully
+ * fetched content will be converted.
+ */
+public class BasicFields
+ extends Configured
+ implements Tool {
+
+ public static final Log LOG = LogFactory.getLog(BasicFields.class);
+
+ /**
+ * Runs the Extractor job. Extracts basic fields from segments.
+ *
+ * @param nodeDb The node database
+ * @param segment A single segment to process.
+ * @param outputDir The extractor output.
+ *
+ * @throws IOException If an error occurs while processing the segment.
+ */
+ private void runExtractor(Path nodeDb, Path segment, Path outputDir)
+ throws IOException {
+
+ LOG.info("BasicFields: starting extractor");
+ JobConf job = new NutchJob(getConf());
+ job.setJobName("BasicFields " + outputDir);
+
+ LOG.info("BasicFields: extractor adding segment: " + segment);
+ FileInputFormat.addInputPath(job, new Path(segment,
+ CrawlDatum.FETCH_DIR_NAME));
+ FileInputFormat.addInputPath(job, new Path(segment, ParseData.DIR_NAME));
+ FileInputFormat.addInputPath(job, new Path(segment, ParseText.DIR_NAME));
+ FileInputFormat.addInputPath(job, nodeDb);
+ job.setInputFormat(SequenceFileInputFormat.class);
+ job.setMapperClass(Extractor.class);
+ job.setReducerClass(Extractor.class);
+ FileOutputFormat.setOutputPath(job, outputDir);
+ job.setOutputFormat(SequenceFileOutputFormat.class);
+ job.setMapOutputKeyClass(Text.class);
+ job.setMapOutputValueClass(ObjectWritable.class);
+ job.setOutputKeyClass(Text.class);
+ job.setOutputValueClass(FieldsWritable.class);
+
+ JobClient.runJob(job);
+ if (LOG.isInfoEnabled()) {
+ LOG.info("BasicFields: finished extractor");
+ }
+ }
+
+ /**
+ * Runs the Flipper job. Flipper is the first of a two part job to implement
+ * redirect logic.
+ *
+ * @param basicFields The basic fields temporary output.
+ * @param nodeDb The node database.
+ * @param outputDir The flipper output.
+ *
+ * @throws IOException If an error occurs while processing.
+ */
+ private void runFlipper(Path basicFields, Path nodeDb, Path outputDir)
+ throws IOException {
+
+ LOG.info("BasicFields: starting flipper");
+ JobConf job = new NutchJob(getConf());
+ job.setJobName("BasicFields " + outputDir);
+ FileInputFormat.addInputPath(job, nodeDb);
+ FileInputFormat.addInputPath(job, basicFields);
+ job.setInputFormat(SequenceFileInputFormat.class);
+ job.setMapperClass(Flipper.class);
+ job.setReducerClass(Flipper.class);
+ FileOutputFormat.setOutputPath(job, outputDir);
+ job.setOutputFormat(SequenceFileOutputFormat.class);
+ job.setMapOutputKeyClass(Text.class);
+ job.setMapOutputValueClass(ObjectWritable.class);
+ job.setOutputKeyClass(Text.class);
+ job.setOutputValueClass(LinkDatum.class);
+
+ JobClient.runJob(job);
+ if (LOG.isInfoEnabled()) {
+ LOG.info("BasicFields: finished flipper");
+ }
+ }
+
+ /**
+ * Runs the Scorer job. Scorer is the second of a two part job to implement
+ * redirect logic.
+ *
+ * @param basicFields The basic fields temporary output.
+ * @param links The temporary output holding urls and any redirects.
+ * @param outputDir The scorer output.
+ *
+ * @throws IOException If an error occurs while processing.
+ */
+ private void runScorer(Path basicFields, Path links, Path outputDir)
+ throws IOException {
+
+ LOG.info("BasicFields: starting scorer");
+ JobConf job = new NutchJob(getConf());
+ job.setJobName("BasicFields " + outputDir);
+ FileInputFormat.addInputPath(job, links);
+ FileInputFormat.addInputPath(job, basicFields);
+ job.setInputFormat(SequenceFileInputFormat.class);
+ job.setMapperClass(Scorer.class);
+ job.setReducerClass(Scorer.class);
+ FileOutputFormat.setOutputPath(job, outputDir);
+ job.setOutputFormat(SequenceFileOutputFormat.class);
+ job.setMapOutputKeyClass(Text.class);
+ job.setMapOutputValueClass(ObjectWritable.class);
+ job.setOutputKeyClass(Text.class);
+ job.setOutputValueClass(FieldsWritable.class);
+
+ JobClient.runJob(job);
+ if (LOG.isInfoEnabled()) {
+ LOG.info("BasicFields: finished scorer");
+ }
+ }
+
+ /**
+ * Runs the Merger job. Merger ensures that the most recent set of fields for
+ * any given url is collected.
+ *
+ * @param basicFields The basic fields final output.
+ * @param outputDir The merger output.
+ *
+ * @throws IOException If an error occurs while processing.
+ */
+ private void runMerger(Path[] basicFields, Path outputDir)
+ throws IOException {
+
+ LOG.info("BasicFields: starting merger");
+ JobConf job = new NutchJob(getConf());
+ job.setJobName("BasicFields " + outputDir);
+ for (Path basic : basicFields) {
+ FileInputFormat.addInputPath(job, basic);
+ }
+ job.setInputFormat(SequenceFileInputFormat.class);
+ job.setReducerClass(Merger.class);
+ FileOutputFormat.setOutputPath(job, outputDir);
+ job.setOutputFormat(SequenceFileOutputFormat.class);
+ job.setOutputKeyClass(Text.class);
+ job.setOutputValueClass(FieldsWritable.class);
+
+ JobClient.runJob(job);
+ if (LOG.isInfoEnabled()) {
+ LOG.info("BasicFields: finished merger");
+ }
+ }
+
+ /**
+ * Extracts basic fields from a single segment.
+ */
+ private static class Extractor
+ extends Configured
+ implements Mapper<Text, Writable, Text, ObjectWritable>,
+ Reducer<Text, ObjectWritable, Text, FieldsWritable> {
+
+ private int MAX_TITLE_LENGTH;
+ private Configuration conf;
+
+ /**
+ * Default constructor.
+ */
+ public Extractor() {
+
+ }
+
+ /**
+ * Configurable constructor.
+ */
+ public Extractor(Configuration conf) {
+ setConf(conf);
+ }
+
+ /**
+ * Configures the job.
+ */
+ public void configure(JobConf conf) {
+ this.conf = conf;
+ this.MAX_TITLE_LENGTH = conf.getInt("indexer.max.title.length", 100);
+ }
+
+ public void close() {
+ }
+
+ /**
+ * Wraps values in ObjectWritable.
+ */
+ public void map(Text key, Writable value,
+ OutputCollector<Text, ObjectWritable> output, Reporter reporter)
+ throws IOException {
+ ObjectWritable objWrite = new ObjectWritable();
+ objWrite.set(value);
+ output.collect(key, objWrite);
+ }
+
+ /**
+ * Creates basic fields from a single segment.
+ */
+ public void reduce(Text key, Iterator<ObjectWritable> values,
+ OutputCollector<Text, FieldsWritable> output, Reporter reporter)
+ throws IOException {
+
+ Node nodeDb = null;
+ List<CrawlDatum> fetchDatums = new ArrayList<CrawlDatum>();
+ ParseData parseData = null;
+ ParseText parseText = null;
+ List<FieldWritable> fieldsList = new ArrayList<FieldWritable>();
+
+ // assign values, url must be successfully fetched and parsed
+ while (values.hasNext()) {
+
+ ObjectWritable objWrite = values.next();
+ Object value = objWrite.get();
+ if (value instanceof CrawlDatum) {
+ CrawlDatum datum = (CrawlDatum)value;
+ if (datum.getStatus() == CrawlDatum.STATUS_FETCH_SUCCESS) {
+ fetchDatums.add(datum);
+ }
+ }
+ else if (value instanceof Node) {
+ nodeDb = (Node)value;
+ }
+ else if (value instanceof ParseData
+ && ((ParseData)value).getStatus().isSuccess()) {
+ parseData = (ParseData)value;
+ }
+ else if (value instanceof ParseText) {
+ parseText = (ParseText)value;
+ }
+ }
+
+ // if not successfully fetched and parsed then stop processing
+ int numDatums = fetchDatums.size();
+ if (numDatums == 0 || nodeDb == null || parseText == null
+ || parseData == null) {
+ return;
+ }
+
+ // get the most recent fetch time, this is duplicates inside of a single
+ // segment, usually due to redirects
+ CrawlDatum fetchDatum = null;
+ long mostRecent = 0L;
+ for (CrawlDatum cur : fetchDatums) {
+ long fetchTime = cur.getFetchTime();
+ if (fetchDatum == null || fetchTime > mostRecent) {
+ fetchDatum = cur;
+ mostRecent = fetchTime;
+ }
+ }
+
+ // get parse metadata
+ Metadata metadata = parseData.getContentMeta();
+ Parse parse = new ParseImpl(parseText, parseData);
+
+ // handle redirect urls
+ Text reprUrlText = (Text)fetchDatum.getMetaData().get(
+ Nutch.WRITABLE_REPR_URL_KEY);
+ String reprUrl = reprUrlText != null ? reprUrlText.toString() : null;
+ String url = key.toString();
+ String fieldUrl = (reprUrl != null) ? reprUrl : url;
+ String host = URLUtil.getHost(fieldUrl);
+
+ // add segment, used to map from merged index back to segment files
+ FieldWritable segField = new FieldWritable(Fields.SEGMENT,
+ metadata.get(Nutch.SEGMENT_NAME_KEY), FieldType.CONTENT, false, true,
+ false);
+ fieldsList.add(segField);
+
+ // add digest, used by dedup
+ FieldWritable digestField = new FieldWritable(Fields.DIGEST,
+ metadata.get(Nutch.SIGNATURE_KEY), FieldType.CONTENT, false, true,
+ false);
+ fieldsList.add(digestField);
+
+ // url is both stored and indexed, so it's both searchable and returned
+ fieldsList.add(new FieldWritable(Fields.URL, fieldUrl, FieldType.CONTENT,
+ true, true, true));
+ fieldsList.add(new FieldWritable(Fields.SEG_URL, url, FieldType.CONTENT,
+ false, true, false));
+
+ if (reprUrl != null) {
+ // also store original url as both stored and indexes
+ fieldsList.add(new FieldWritable(Fields.ORIG_URL, url,
+ FieldType.CONTENT, true, true, true));
+ }
+
+ if (host != null) {
+ // add host as un-stored, indexed and tokenized
+ FieldWritable hostField = new FieldWritable(Fields.HOST, host,
+ FieldType.CONTENT, true, false, true);
+ fieldsList.add(hostField);
+
+ // add site as un-stored, indexed and un-tokenized
+ FieldWritable siteField = new FieldWritable(Fields.SITE, host,
+ FieldType.CONTENT, true, false, false);
+ fieldsList.add(siteField);
+ }
+
+ // content is indexed, so that it's searchable, but not stored in index
+ fieldsList.add(new FieldWritable(Fields.CONTENT, parse.getText(),
+ FieldType.CONTENT, true, false, true));
+
+ // title
+ String title = parse.getData().getTitle();
+ if (title.length() > MAX_TITLE_LENGTH) { // truncate title if needed
+ title = title.substring(0, MAX_TITLE_LENGTH);
+ }
+ // add title indexed and stored so that it can be displayed
+ fieldsList.add(new FieldWritable(Fields.TITLE, title, FieldType.CONTENT,
+ true, true, true));
+
+ // add cached content/summary display policy, if available
+ String caching = parse.getData().getMeta(Nutch.CACHING_FORBIDDEN_KEY);
+ if (caching != null && !caching.equals(Nutch.CACHING_FORBIDDEN_NONE)) {
+ fieldsList.add(new FieldWritable(Fields.CACHE, caching,
+ FieldType.CONTENT, false, true, false));
+ }
+
+ // add timestamp when fetched, for deduplication
+ fieldsList.add(new FieldWritable(Fields.TSTAMP, DateTools.timeToString(
+ fetchDatum.getFetchTime(), DateTools.Resolution.MILLISECOND),
+ FieldType.CONTENT, false, true, false));
+
+ FieldsWritable fields = new FieldsWritable();
+ fields.setFieldsList(fieldsList);
+ output.collect(key, fields);
+ }
+ }
+
+ /**
+ * Runs the first part of redirect logic. Breaks out fields if a page
+ * contains a redirect.
+ */
+ public static class Flipper
+ extends Configured
+ implements Mapper<Text, Writable, Text, ObjectWritable>,
+ Reducer<Text, ObjectWritable, Text, LinkDatum> {
+
+ private JobConf conf;
+
+ /**
+ * Configures the job.
+ */
+ public void configure(JobConf conf) {
+ this.conf = conf;
+ }
+
+ public void close() {
+ }
+
+ /**
+ * Breaks out the collection of fields for url and redirects if necessary.
+ */
+ public void map(Text key, Writable value,
+ OutputCollector<Text, ObjectWritable> output, Reporter reporter)
+ throws IOException {
+
+ ObjectWritable objUrl = new ObjectWritable();
+ objUrl.set(key);
+
+ if (value instanceof FieldsWritable) {
+
+ // collect the fields for the url
+ FieldsWritable fields = (FieldsWritable)value;
+ FieldWritable url = fields.getField(Fields.URL);
+ FieldWritable orig = fields.getField(Fields.ORIG_URL);
+ output.collect(new Text(url.getValue()), objUrl);
+
+ // collect for the orig / redirect url if one exists
+ if (orig != null) {
+ output.collect(new Text(orig.getValue()), objUrl);
+ }
+ }
+ else {
+
+ // anything else passes through
+ ObjectWritable objWrite = new ObjectWritable();
+ objWrite.set(value);
+ output.collect(key, objWrite);
+ }
+ }
+
+ /**
+ * Collects redirect and original links for a given url key. This will be
+ * used in the Scorer to handle redirects.
+ */
+ public void reduce(Text key, Iterator<ObjectWritable> values,
+ OutputCollector<Text, LinkDatum> output, Reporter reporter)
+ throws IOException {
+
+ Node node = null;
+ List<String> urls = new ArrayList<String>();
+
+ while (values.hasNext()) {
+ ObjectWritable objWrite = values.next();
+ Object obj = objWrite.get();
+ if (obj instanceof Node) {
+ node = (Node)obj;
+ }
+ else if (obj instanceof Text) {
+ urls.add(obj.toString());
+ }
+ }
+
+ if (urls.size() > 0) {
+ float score = (node != null) ? node.getInlinkScore() : 0.0f;
+ for (String url : urls) {
+ LinkDatum datum = new LinkDatum(key.toString());
+ datum.setScore(score);
+ output.collect(new Text(url), datum);
+ }
+ }
+ }
+ }
+
+ /**
+ * The Scorer job sets the boost field from the NodeDb score.
+ *
+ * It also runs the second part of redirect logic. Determining the highest
+ * scoring url for pages that contain redirects.
+ */
+ public static class Scorer
+ extends Configured
+ implements Mapper<Text, Writable, Text, ObjectWritable>,
+ Reducer<Text, ObjectWritable, Text, FieldsWritable> {
+
+ private JobConf conf;
+
+ /**
+ * Configures the job.
+ */
+ public void configure(JobConf conf) {
+ this.conf = conf;
+ }
+
+ public void close() {
+ }
+
+ /**
+ * Wraps values in ObjectWritable.
+ */
+ public void map(Text key, Writable value,
+ OutputCollector<Text, ObjectWritable> output, Reporter reporter)
+ throws IOException {
+
+ ObjectWritable objWrite = new ObjectWritable();
+ objWrite.set(value);
+ output.collect(key, objWrite);
+ }
+
+ /**
+ * Sets a document boost field from the NodeDb and determines the best
+ * scoring url for pages that have rediects. Uses the highest scoring url
+ * as the display url in the index.
+ */
+ public void reduce(Text key, Iterator<ObjectWritable> values,
+ OutputCollector<Text, FieldsWritable> output, Reporter reporter)
+ throws IOException {
+
+ FieldsWritable fields = null;
+ List<LinkDatum> datums = new ArrayList<LinkDatum>();
+
+ while (values.hasNext()) {
+ ObjectWritable objWrite = values.next();
+ Object obj = objWrite.get();
+ if (obj instanceof FieldsWritable) {
+ fields = (FieldsWritable)obj;
+ }
+ else if (obj instanceof LinkDatum) {
+ datums.add((LinkDatum)obj);
+ }
+ }
+
+ int numDatums = datums.size();
+ if (fields != null && numDatums > 0) {
+
+ // if no redirect for the page just assign the linkrank boost
+ List<FieldWritable> fieldsList = fields.getFieldsList();
+ if (numDatums == 1) {
+ float linkRank = datums.get(0).getScore();
+ fieldsList.add(new FieldWritable(Fields.BOOST, "linkrank",
+ FieldType.BOOST, linkRank));
+ output.collect(new Text(key), fields);
+ }
+ else {
+
+ // get both the url and any rediect url stored
+ FieldWritable url = fields.getField(Fields.URL);
+ FieldWritable orig = fields.getField(Fields.ORIG_URL);
+ float urlScore = 0.0f;
+ float origScore = 0.0f;
+
+ // get the scores for each
+ for (LinkDatum datum : datums) {
+ String curUrl = datum.getUrl();
+ if (curUrl.equals(url.getValue())) {
+ urlScore = datum.getScore();
+ }
+ else if (curUrl.equals(orig.getValue())) {
+ origScore = datum.getScore();
+ }
+ }
+
+ // if the highest scoring url is not the one currently displayed in
+ // the index under the current basic fields, then switch it
+ String urlKey = url.getValue();
+ float linkRank = urlScore;
+ if (origScore > urlScore) {
+ url.setName(Fields.ORIG_URL);
+ orig.setName(Fields.URL);
+
+ // We also need to fix the host because we are changing urls
+ String host = URLUtil.getHost(orig.getValue());
+ if (host != null) {
+ fieldsList.remove(fields.getField(Fields.SITE));
+ fieldsList.remove(fields.getField(Fields.HOST));
+ fieldsList.add(new FieldWritable(Fields.HOST, host,
+ FieldType.CONTENT, true, false, true));
+ fieldsList.add(new FieldWritable(Fields.SITE, host,
+ FieldType.CONTENT, true, false, false));
+ }
+
+ linkRank = origScore;
+ urlKey = orig.getValue();
+ }
+
+ // create the final document boost field
+ fieldsList.add(new FieldWritable(Fields.BOOST, "linkrank",
+ FieldType.BOOST, linkRank));
+ output.collect(new Text(urlKey), fields);
+ }
+ }
+ }
+ }
+
+ /**
+ * Merges output of all segments fields collecting only the most recent set
+ * of fields for any given url.
+ */
+ public static class Merger
+ extends Configured
+ implements Reducer<Text, FieldsWritable, Text, FieldsWritable> {
+
+ private JobConf conf;
+
+ /**
+ * Configures the job.
+ */
+ public void configure(JobConf conf) {
+ this.conf = conf;
+ }
+
+ public void close() {
+ }
+
+ /**
+ * Collects the most recent set of fields for any url.
+ */
+ public void reduce(Text key, Iterator<FieldsWritable> values,
+ OutputCollector<Text, FieldsWritable> output, Reporter reporter)
+ throws IOException {
+
+ List<FieldsWritable> fields = new ArrayList<FieldsWritable>();
+
+ // collects the various sets of fields
+ while (values.hasNext()) {
+ fields.add((FieldsWritable)WritableUtils.clone(values.next(), conf));
+ }
+
+ // if only one set of fields for a given url passthrough
+ FieldsWritable outFields = null;
+ int numFields = fields.size();
+ if (numFields == 1) {
+ outFields = fields.get(0);
+ }
+ else if (numFields > 1) {
+
+ // more than one set of fields means url has been fetched more than
+ // once, collect only the most recent set of fields
+ FieldsWritable mostRecent = null;
+ long recentTime = 0L;
+ for (int i = 0; i < numFields; i++) {
+ FieldsWritable cur = fields.get(i);
+ String tStampStr = cur.getField(Fields.TSTAMP).getValue();
+ long timestamp = Long.parseLong(tStampStr);
+ if (mostRecent == null || recentTime < timestamp) {
+ recentTime = timestamp;
+ mostRecent = cur;
+ }
+ }
+
+ outFields = mostRecent;
+ }
+
+ output.collect(key, outFields);
+ }
+ }
+
+ /**
+ * Runs the BasicFields jobs for every segment and aggregates and filters
+ * the output to create a final database of FieldWritable objects.
+ *
+ * @param nodeDb The node database.
+ * @param segments The array of segments to process.
+ * @param output The BasicFields output.
+ *
+ * @throws IOException If an error occurs while processing the segments.
+ */
+ public void createFields(Path nodeDb, Path[] segments, Path output)
+ throws IOException {
+
+ Configuration conf = getConf();
+ FileSystem fs = FileSystem.get(conf);
+ Path tempOutput = new Path(output.toString() + "-temp");
+ fs.mkdirs(tempOutput);
+ int numSegments = segments.length;
+ Path[] basicFields = new Path[numSegments];
+
+ // one pass per segment to extract and create the basic fields
+ for (int i = 0; i < numSegments; i++) {
+
+ Path segment = segments[i];
+ Path segOutput = new Path(tempOutput, String.valueOf(i));
+ Path tempBasic = new Path(tempOutput, "basic-"
+ + Integer.toString(new Random().nextInt(Integer.MAX_VALUE)));
+ Path tempFlip = new Path(tempOutput, "flip-"
+ + Integer.toString(new Random().nextInt(Integer.MAX_VALUE)));
+
+ runExtractor(nodeDb, segment, tempBasic);
+ runFlipper(tempBasic, nodeDb, tempFlip);
+ runScorer(tempBasic, tempFlip, segOutput);
+
+ fs.delete(tempBasic, true);
+ fs.delete(tempFlip, true);
+ basicFields[i] = segOutput;
+ }
+
+ // merge all of the segments and delete any temporary output
+ runMerger(basicFields, output);
+ fs.delete(tempOutput, true);
+ }
+
+ public static void main(String[] args)
+ throws Exception {
+ int res = ToolRunner.run(NutchConfiguration.create(), new BasicFields(),
+ args);
+ System.exit(res);
+ }
+
+ /**
+ * Runs the BasicFields tool.
+ */
+ public int run(String[] args)
+ throws Exception {
+
+ Options options = new Options();
+ Option helpOpts = OptionBuilder.withArgName("help").withDescription(
+ "show this help message").create("help");
+ Option outputOpts = OptionBuilder.withArgName("output").hasArg().withDescription(
+ "the output index directory").create("output");
+ Option webGraphOpts = OptionBuilder.withArgName("webgraphdb").hasArg().withDescription(
+ "the webgraphdb to use").create("webgraphdb");
+ Option segOpts = OptionBuilder.withArgName("segment").hasArgs().withDescription(
+ "the segment(s) to use").create("segment");
+ options.addOption(helpOpts);
+ options.addOption(webGraphOpts);
+ options.addOption(segOpts);
+ options.addOption(outputOpts);
+
+ CommandLineParser parser = new GnuParser();
+ try {
+
+ CommandLine line = parser.parse(options, args);
+ if (line.hasOption("help") || !line.hasOption("webgraphdb")
+ || !line.hasOption("output") || !line.hasOption("segment")) {
+ HelpFormatter formatter = new HelpFormatter();
+ formatter.printHelp("BasicFields", options);
+ return -1;
+ }
+
+ // get the command line options and all of the segments
+ String webGraphDb = line.getOptionValue("webgraphdb");
+ String output = line.getOptionValue("output");
+ String[] segments = line.getOptionValues("segment");
+ Path[] segPaths = new Path[segments.length];
+ for (int i = 0; i < segments.length; i++) {
+ segPaths[i] = new Path(segments[i]);
+ }
+
+ createFields(new Path(webGraphDb, WebGraph.NODE_DIR), segPaths, new Path(
+ output));
+ return 0;
+ }
+ catch (Exception e) {
+ LOG.fatal("BasicFields: " + StringUtils.stringifyException(e));
+ return -2;
+ }
+ }
+}
diff --git a/src/java/org/apache/nutch/indexer/field/CustomFields.java b/src/java/org/apache/nutch/indexer/field/CustomFields.java
new file mode 100644
index 000000000..d378898c1
--- /dev/null
+++ b/src/java/org/apache/nutch/indexer/field/CustomFields.java
@@ -0,0 +1,425 @@
+package org.apache.nutch.indexer.field;
+
+import java.io.IOException;
+import java.io.InputStream;
+import java.util.ArrayList;
+import java.util.Enumeration;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Map;
+import java.util.Properties;
+import java.util.Random;
+import java.util.Set;
+
+import org.apache.commons.cli.CommandLine;
+import org.apache.commons.cli.CommandLineParser;
+import org.apache.commons.cli.GnuParser;
+import org.apache.commons.cli.HelpFormatter;
+import org.apache.commons.cli.Option;
+import org.apache.commons.cli.OptionBuilder;
+import org.apache.commons.cli.Options;
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.apache.hadoop.conf.Configuration;
+import org.apache.hadoop.conf.Configured;
+import org.apache.hadoop.fs.FileSystem;
+import org.apache.hadoop.fs.Path;
+import org.apache.hadoop.io.LongWritable;
+import org.apache.hadoop.io.ObjectWritable;
+import org.apache.hadoop.io.Text;
+import org.apache.hadoop.io.Writable;
+import org.apache.hadoop.mapred.FileInputFormat;
+import org.apache.hadoop.mapred.FileOutputFormat;
+import org.apache.hadoop.mapred.JobClient;
+import org.apache.hadoop.mapred.JobConf;
+import org.apache.hadoop.mapred.Mapper;
+import org.apache.hadoop.mapred.OutputCollector;
+import org.apache.hadoop.mapred.Reducer;
+import org.apache.hadoop.mapred.Reporter;
+import org.apache.hadoop.mapred.SequenceFileInputFormat;
+import org.apache.hadoop.mapred.SequenceFileOutputFormat;
+import org.apache.hadoop.mapred.TextInputFormat;
+import org.apache.hadoop.util.StringUtils;
+import org.apache.hadoop.util.Tool;
+import org.apache.hadoop.util.ToolRunner;
+import org.apache.nutch.util.NutchConfiguration;
+import org.apache.nutch.util.NutchJob;
+
+/**
+ * Creates custom FieldWritable objects from a text file containing field
+ * information including field name, value, and optional boost and fields type
+ * (as needed by FieldWritable objects).
+ *
+ * An input text file to CustomFields would be tab separated and would look
+ * similar to this:
+ *
+ * <pre>
+ * http://www.apache.org\tlang\ten\t5.0\tCONTENT
+ * http://lucene.apache.org\tlang\tde
+ * </pre>
+ *
+ * The only required fields are url, name and value. Custom fields are
+ * configured through the custom-fields.xml file in the classpath. The config
+ * file allow you to set defaults for whether a field is indexed, stored, and
+ * tokenized, boosts on a field, and whether a field can output multiple values
+ * under the same key.
+ *
+ * The purpose of the CustomFields job is to allow better integration with
+ * technologies such as Hadoop Streaming. Streaming jobs can be created in any
+ * programming language, can output the text file needed by the CustomFields
+ * job, and those fields can then be included in the index.
+ *
+ * The concept of custom fields requires two separate pieces. The indexing piece
+ * and the query piece. The indexing piece is handled by the CustomFields job.
+ * The query piece is handled by the query-custom plugin.
+ *
+ * <b>Important:</b><br> <i>Currently, because of the way the query plugin
+ * architecture works, custom fields names must be added to the fields parameter
+ * in the query-custom plugin plugin.xml file in order to be queried.</i>
+ *
+ * The CustomFields tool accepts one or more directories containing text files
+ * in the appropriate custom field format. These files are then turned into
+ * FieldWritable objects to be included in the index.
+ */
+public class CustomFields
+ extends Configured
+ implements Tool {
+
+ public static final Log LOG = LogFactory.getLog(CustomFields.class);
+
+ /**
+ * MapReduce job that converts text values into FieldWritable objects.
+ *
+ * @param inputs The directories with text files to convert.
+ * @param output The converter output directory.
+ *
+ * @throws IOException If an error occurs while converting.
+ */
+ private void runConverter(Path[] inputs, Path output)
+ throws IOException {
+
+ JobConf converter = new NutchJob(getConf());
+ converter.setJobName("CustomFields Converter");
+ for (int i = 0; i < inputs.length; i++) {
+ FileInputFormat.addInputPath(converter, inputs[i]);
+ }
+ FileOutputFormat.setOutputPath(converter, output);
+ converter.setInputFormat(TextInputFormat.class);
+ converter.setMapperClass(Converter.class);
+ converter.setReducerClass(Converter.class);
+ converter.setMapOutputKeyClass(Text.class);
+ converter.setMapOutputValueClass(FieldWritable.class);
+ converter.setOutputKeyClass(Text.class);
+ converter.setOutputValueClass(FieldWritable.class);
+ converter.setOutputFormat(SequenceFileOutputFormat.class);
+
+ LOG.info("Starting converter job");
+ try {
+ JobClient.runJob(converter);
+ }
+ catch (IOException e) {
+ LOG.error(StringUtils.stringifyException(e));
+ throw e;
+ }
+ LOG.info("Finished converter job.");
+ }
+
+ /**
+ * Aggregated multiple FieldWritable objects with the same name. Depending on
+ * settings in the custom-fields.xml file, a field may one or more fields.
+ * This jobs aggregates fields and then collects based on the configuration
+ * settings.
+ *
+ * @param basicFields The basicfields FieldWritable objects.
+ * @param converted The converted custom field objects.
+ * @param output The final output directory for custom field objects.
+ *
+ * @throws IOException If an error occurs while converting.
+ */
+ private void runCollector(Path basicFields, Path converted, Path output)
+ throws IOException {
+
+ JobConf collector = new NutchJob(getConf());
+ collector.setJobName("CustomFields Collector");
+ FileInputFormat.addInputPath(collector, converted);
+ FileInputFormat.addInputPath(collector, basicFields);
+ FileOutputFormat.setOutputPath(collector, output);
+ collector.setInputFormat(SequenceFileInputFormat.class);
+ collector.setMapOutputKeyClass(Text.class);
+ collector.setMapOutputValueClass(ObjectWritable.class);
+ collector.setMapperClass(Collector.class);
+ collector.setReducerClass(Collector.class);
+ collector.setOutputKeyClass(Text.class);
+ collector.setOutputValueClass(FieldWritable.class);
+ collector.setOutputFormat(SequenceFileOutputFormat.class);
+
+ LOG.info("Starting collector job");
+ try {
+ JobClient.runJob(collector);
+ }
+ catch (IOException e) {
+ LOG.error(StringUtils.stringifyException(e));
+ throw e;
+ }
+ LOG.info("Finished collector job.");
+ }
+
+ /**
+ * Converts text values into FieldWritable objects.
+ */
+ public static class Converter
+ extends Configured
+ implements Mapper<LongWritable, Text, Text, FieldWritable>,
+ Reducer<Text, FieldWritable, Text, FieldWritable> {
+
+ private JobConf conf;
+ private Map<String, boolean[]> flagMap = new HashMap<String, boolean[]>();
+ private Set<String> multiFields = new HashSet<String>();
+
+ public Converter() {
+ }
+
+ public Converter(Configuration conf) {
+ setConf(conf);
+ }
+
+ public void configure(JobConf conf) {
+
+ try {
+
+ // get the file system and the configuration file from the classpath
+ this.conf = conf;
+ FileSystem fs = FileSystem.get(conf);
+ String configFile = conf.get("custom.fields.config",
+ "custom-fields.xml");
+ LOG.info("Reading configuration field configuration from " + configFile);
+ Properties customFieldProps = new Properties();
+ InputStream fis = conf.getConfResourceAsInputStream(configFile);
+ if (fis == null) {
+ throw new IOException("Was unable to open " + configFile);
+ }
+
+ // load the configuration file as properties
+ customFieldProps.loadFromXML(fis);
+
+ // loop through the properties setting field flags
+ Enumeration propKeys = customFieldProps.keys();
+ while (propKeys.hasMoreElements()) {
+ String prop = (String)propKeys.nextElement();
+ if (prop.endsWith(".name")) {
+ String propName = prop.substring(0, prop.length() - 5);
+ String name = customFieldProps.getProperty(prop);
+
+ String indexedProp = customFieldProps.getProperty(propName
+ + ".indexed");
+ String storedProp = customFieldProps.getProperty(propName
+ + ".stored");
+ String tokProp = customFieldProps.getProperty(propName
+ + ".tokenized");
+ boolean indexed = (indexedProp.equalsIgnoreCase("yes")
+ || indexedProp.equalsIgnoreCase("true") || indexedProp.equalsIgnoreCase("on"));
+ boolean stored = (storedProp.equalsIgnoreCase("yes")
+ || storedProp.equalsIgnoreCase("true") || storedProp.equalsIgnoreCase("on"));
+ boolean tokenized = (tokProp.equalsIgnoreCase("yes")
+ || tokProp.equalsIgnoreCase("true") || tokProp.equalsIgnoreCase("on"));
+ boolean[] flags = {indexed, stored, tokenized};
+ flagMap.put(name, flags);
+
+ String multiProp = customFieldProps.getProperty(propName + ".multi");
+ boolean multi = (multiProp.equalsIgnoreCase("yes")
+ || multiProp.equalsIgnoreCase("true") || multiProp.equalsIgnoreCase("on"));
+ if (multi) {
+ multiFields.add(name);
+ }
+ }
+ }
+ }
+ catch (Exception e) {
+ LOG.error("Error loading custom field properties:\n"
+ + StringUtils.stringifyException(e));
+ }
+ }
+
+ public void map(LongWritable key, Text value,
+ OutputCollector<Text, FieldWritable> output, Reporter reporter)
+ throws IOException {
+
+ // split the file on tabs
+ String line = value.toString();
+ String[] fields = line.split("\t");
+ if (fields.length >= 3) {
+
+ // fields must be in a specific order, default values for optional fields
+ String url = fields[0];
+ String fieldName = fields[1];
+ String fieldVal = fields[2];
+ String fieldScore = (fields.length > 3 ? fields[3] : null);
+ String fieldType = (fields.length > 4 ? fields[4] : "CONTENT").toUpperCase();
+
+ // creates the FieldWritable objects and collects
+ boolean[] flags = flagMap.get(fieldName);
+ if (flags != null) {
+ FieldWritable field = null;
+ if (fieldScore != null) {
+ field = new FieldWritable(fieldName, fieldVal,
+ FieldType.valueOf(fieldType), Float.parseFloat(fieldScore),
+ flags[0], flags[1], flags[2]);
+ }
+ else {
+ field = new FieldWritable(fieldName, fieldVal,
+ FieldType.valueOf(fieldType), flags[0], flags[1], flags[2]);
+ }
+ output.collect(new Text(url), field);
+ }
+ }
+ }
+
+ public void reduce(Text key, Iterator<FieldWritable> values,
+ OutputCollector<Text, FieldWritable> output, Reporter reporter)
+ throws IOException {
+
+ // if multiple fields are allowed collect all of them, if not allowed
+ // and multiple fields are present all of the values are ignored
+ Set<String> multiSet = new HashSet<String>();
+ while (values.hasNext()) {
+ FieldWritable field = values.next();
+ String name = field.getName();
+ boolean isMulti = multiFields.contains(name);
+ if (isMulti || (!isMulti && !multiSet.contains(name))) {
+ output.collect(key, field);
+ multiSet.add(name);
+ }
+ else {
+ LOG.info("Ignoring multiple " + name + " fields for "
+ + key.toString());
+ }
+ }
+ }
+
+ public void close() {
+ }
+ }
+
+ /**
+ * Aggregates FieldWritable objects by the same name for the same URL. These
+ * objects are them filtered for multiple values against configuration
+ * settings.
+ */
+ public static class Collector
+ extends Configured
+ implements Mapper<Text, Writable, Text, ObjectWritable>,
+ Reducer<Text, ObjectWritable, Text, FieldWritable> {
+
+ private JobConf conf;
+
+ public void configure(JobConf conf) {
+ this.conf = conf;
+ }
+
+ public void close() {
+ }
+
+ public void map(Text key, Writable value,
+ OutputCollector<Text, ObjectWritable> output, Reporter reporter)
+ throws IOException {
+
+ ObjectWritable objWrite = new ObjectWritable();
+ objWrite.set(value);
+ output.collect(key, objWrite);
+ }
+
+ public void reduce(Text key, Iterator<ObjectWritable> values,
+ OutputCollector<Text, FieldWritable> output, Reporter reporter)
+ throws IOException {
+
+ FieldsWritable basicFields = null;
+ List<FieldWritable> customFields = new ArrayList<FieldWritable>();
+
+ while (values.hasNext()) {
+ ObjectWritable objWrite = values.next();
+ Object obj = objWrite.get();
+ if (obj instanceof FieldWritable) {
+ customFields.add((FieldWritable)obj);
+ }
+ else if (obj instanceof FieldsWritable) {
+ basicFields = (FieldsWritable)obj;
+ }
+ }
+
+ if (basicFields != null && customFields.size() > 0) {
+ for (int i = 0; i < customFields.size(); i++) {
+ output.collect(key, customFields.get(i));
+ }
+ }
+ }
+ }
+
+ void createFields(Path basicFields, Path[] inputs, Path output)
+ throws IOException {
+
+ Configuration conf = getConf();
+ FileSystem fs = FileSystem.get(conf);
+ Path tempFields = new Path(output + "-"
+ + Integer.toString(new Random().nextInt(Integer.MAX_VALUE)));
+ runConverter(inputs, tempFields);
+ runCollector(basicFields, tempFields, output);
+ fs.delete(tempFields, true);
+ }
+
+ public static void main(String[] args)
+ throws Exception {
+ int res = ToolRunner.run(NutchConfiguration.create(), new CustomFields(),
+ args);
+ System.exit(res);
+ }
+
+ /**
+ * Runs the CustomFields job.
+ */
+ public int run(String[] args)
+ throws Exception {
+
+ Options options = new Options();
+ Option helpOpts = OptionBuilder.withArgName("help").withDescription(
+ "show this help message").create("help");
+ Option outputOpts = OptionBuilder.withArgName("output").hasArg().withDescription(
+ "the output index directory").create("output");
+ Option inputOpts = OptionBuilder.withArgName("input").hasArgs().withDescription(
+ "the input directories with text field files").create("input");
+ Option basicFieldOpts = OptionBuilder.withArgName("basicfields").hasArg().withDescription(
+ "the basicfields to use").create("basicfields");
+ options.addOption(helpOpts);
+ options.addOption(inputOpts);
+ options.addOption(basicFieldOpts);
+ options.addOption(outputOpts);
+
+ CommandLineParser parser = new GnuParser();
+ try {
+
+ CommandLine line = parser.parse(options, args);
+ if (line.hasOption("help") || !line.hasOption("output")
+ || !line.hasOption("basicfields")) {
+ HelpFormatter formatter = new HelpFormatter();
+ formatter.printHelp("CustomFields", options);
+ return -1;
+ }
+
+ String[] inputs = line.getOptionValues("input");
+ Path[] inputPaths = new Path[inputs.length];
+ for (int i = 0; i < inputs.length; i++) {
+ inputPaths[i] = new Path(inputs[i]);
+ }
+ String output = line.getOptionValue("output");
+ String basicFields = line.getOptionValue("basicfields");
+
+ createFields(new Path(basicFields), inputPaths, new Path(output));
+ return 0;
+ }
+ catch (Exception e) {
+ LOG.fatal("CustomFields: " + StringUtils.stringifyException(e));
+ return -2;
+ }
+ }
+}
diff --git a/src/java/org/apache/nutch/indexer/field/FieldFilter.java b/src/java/org/apache/nutch/indexer/field/FieldFilter.java
new file mode 100644
index 000000000..6edf303ec
--- /dev/null
+++ b/src/java/org/apache/nutch/indexer/field/FieldFilter.java
@@ -0,0 +1,42 @@
+package org.apache.nutch.indexer.field;
+
+import java.util.List;
+
+import org.apache.hadoop.conf.Configurable;
+import org.apache.lucene.document.Document;
+import org.apache.nutch.indexer.IndexingException;
+import org.apache.nutch.plugin.Pluggable;
+
+/**
+ * Filter to manipulate FieldWritable objects for a given url during indexing.
+ *
+ * Field filters are responsible for converting FieldWritable objects into
+ * lucene fields and adding those fields to the Lucene document.
+ */
+public interface FieldFilter
+ extends Pluggable, Configurable {
+
+ final static String X_POINT_ID = FieldFilter.class.getName();
+
+ /**
+ * Returns the document to which fields are being added or null if we are to
+ * stop processing for this url and not add anything to the index. All
+ * FieldWritable objects for a url are aggregated from databases passed into
+ * the FieldIndexer and these fields are then passed into the Field filters.
+ *
+ * It is therefore possible for fields to be added, removed, and changed
+ * before being indexed.
+ *
+ * @param url The url to index.
+ * @param doc The lucene document
+ * @param fields The list of FieldWritable objects representing fields for
+ * the index.
+ * @return The lucene Document or null to stop processing and not index any
+ * content for this url.
+ *
+ * @throws IndexingException If an error occurs during indexing
+ */
+ public Document filter(String url, Document doc, List<FieldWritable> fields)
+ throws IndexingException;
+
+}
diff --git a/src/java/org/apache/nutch/indexer/field/FieldFilters.java b/src/java/org/apache/nutch/indexer/field/FieldFilters.java
new file mode 100644
index 000000000..d846415cd
--- /dev/null
+++ b/src/java/org/apache/nutch/indexer/field/FieldFilters.java
@@ -0,0 +1,117 @@
+package org.apache.nutch.indexer.field;
+
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.apache.hadoop.conf.Configuration;
+import org.apache.lucene.document.Document;
+import org.apache.nutch.indexer.IndexingException;
+import org.apache.nutch.plugin.Extension;
+import org.apache.nutch.plugin.ExtensionPoint;
+import org.apache.nutch.plugin.PluginRepository;
+import org.apache.nutch.plugin.PluginRuntimeException;
+import org.apache.nutch.util.ObjectCache;
+
+/**
+ * The FieldFilters class provides a standard way to collect, order, and run
+ * all FieldFilter implementations that are active in the plugin system.
+ */
+public class FieldFilters {
+
+ public static final String FIELD_FILTER_ORDER = "field.filter.order";
+
+ public final static Log LOG = LogFactory.getLog(FieldFilters.class);
+
+ private FieldFilter[] fieldFilters;
+
+ /**
+ * Configurable constructor.
+ */
+ public FieldFilters(Configuration conf) {
+
+ // get the field filter order, the cache, and all field filters
+ String order = conf.get(FIELD_FILTER_ORDER);
+ ObjectCache objectCache = ObjectCache.get(conf);
+ this.fieldFilters = (FieldFilter[])objectCache.getObject(FieldFilter.class.getName());
+
+ if (this.fieldFilters == null) {
+
+ String[] orderedFilters = null;
+ if (order != null && !order.trim().equals("")) {
+ orderedFilters = order.split("\\s+");
+ }
+ try {
+
+ // get the field filter extension point
+ ExtensionPoint point = PluginRepository.get(conf).getExtensionPoint(
+ FieldFilter.X_POINT_ID);
+ if (point == null) {
+ throw new RuntimeException(FieldFilter.X_POINT_ID + " not found.");
+ }
+
+ // get all of the field filter plugins
+ Extension[] extensions = point.getExtensions();
+ HashMap<String, FieldFilter> filterMap = new HashMap<String, FieldFilter>();
+ for (int i = 0; i < extensions.length; i++) {
+ Extension extension = extensions[i];
+ FieldFilter filter = (FieldFilter)extension.getExtensionInstance();
+ LOG.info("Adding " + filter.getClass().getName());
+ if (!filterMap.containsKey(filter.getClass().getName())) {
+ filterMap.put(filter.getClass().getName(), filter);
+ }
+ }
+
+ // order the filters if necessary
+ if (orderedFilters == null) {
+ objectCache.setObject(FieldFilter.class.getName(),
+ filterMap.values().toArray(new FieldFilter[0]));
+ }
+ else {
+ ArrayList<FieldFilter> filters = new ArrayList<FieldFilter>();
+ for (int i = 0; i < orderedFilters.length; i++) {
+ FieldFilter filter = filterMap.get(orderedFilters[i]);
+ if (filter != null) {
+ filters.add(filter);
+ }
+ }
+ objectCache.setObject(FieldFilter.class.getName(),
+ filters.toArray(new FieldFilter[filters.size()]));
+ }
+ }
+ catch (PluginRuntimeException e) {
+ throw new RuntimeException(e);
+ }
+
+ // set the filters in the cache
+ this.fieldFilters = (FieldFilter[])objectCache.getObject(FieldFilter.class.getName());
+ }
+ }
+
+ /**
+ * Runs all FieldFilter extensions.
+ *
+ * @param url The url to index.
+ * @param doc The lucene index document.
+ * @param fields The lucene fields.
+ *
+ * @return The document to filter or null to not index this document and url.
+ *
+ * @throws IndexingException If an error occurs while running filters.
+ */
+ public Document filter(String url, Document doc, List<FieldWritable> fields)
+ throws IndexingException {
+
+ // loop through and run the field filters
+ for (int i = 0; i < this.fieldFilters.length; i++) {
+ doc = this.fieldFilters[i].filter(url, doc, fields);
+ if (doc == null) {
+ return null;
+ }
+ }
+ return doc;
+ }
+
+}
diff --git a/src/java/org/apache/nutch/indexer/field/FieldIndexer.java b/src/java/org/apache/nutch/indexer/field/FieldIndexer.java
new file mode 100644
index 000000000..e2fefe680
--- /dev/null
+++ b/src/java/org/apache/nutch/indexer/field/FieldIndexer.java
@@ -0,0 +1,304 @@
+package org.apache.nutch.indexer.field;
+
+import java.io.DataInput;
+import java.io.DataOutput;
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Random;
+
+import org.apache.commons.cli.CommandLine;
+import org.apache.commons.cli.CommandLineParser;
+import org.apache.commons.cli.GnuParser;
+import org.apache.commons.cli.HelpFormatter;
+import org.apache.commons.cli.Option;
+import org.apache.commons.cli.OptionBuilder;
+import org.apache.commons.cli.Options;
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.apache.hadoop.conf.Configuration;
+import org.apache.hadoop.conf.Configured;
+import org.apache.hadoop.fs.FileSystem;
+import org.apache.hadoop.fs.Path;
+import org.apache.hadoop.io.Text;
+import org.apache.hadoop.io.Writable;
+import org.apache.hadoop.io.WritableComparable;
+import org.apache.hadoop.io.WritableUtils;
+import org.apache.hadoop.mapred.FileInputFormat;
+import org.apache.hadoop.mapred.FileOutputFormat;
+import org.apache.hadoop.mapred.JobClient;
+import org.apache.hadoop.mapred.JobConf;
+import org.apache.hadoop.mapred.Mapper;
+import org.apache.hadoop.mapred.OutputCollector;
+import org.apache.hadoop.mapred.RecordWriter;
+import org.apache.hadoop.mapred.Reducer;
+import org.apache.hadoop.mapred.Reporter;
+import org.apache.hadoop.mapred.SequenceFileInputFormat;
+import org.apache.hadoop.util.Progressable;
+import org.apache.hadoop.util.StringUtils;
+import org.apache.hadoop.util.Tool;
+import org.apache.hadoop.util.ToolRunner;
+import org.apache.lucene.document.Document;
+import org.apache.lucene.index.IndexWriter;
+import org.apache.nutch.analysis.AnalyzerFactory;
+import org.apache.nutch.analysis.NutchAnalyzer;
+import org.apache.nutch.analysis.NutchDocumentAnalyzer;
+import org.apache.nutch.indexer.IndexingException;
+import org.apache.nutch.indexer.NutchSimilarity;
+import org.apache.nutch.util.LogUtil;
+import org.apache.nutch.util.NutchConfiguration;
+import org.apache.nutch.util.NutchJob;
+
+public class FieldIndexer
+ extends Configured
+ implements Tool, Mapper<Text, Writable, Text, FieldWritable>,
+ Reducer<Text, FieldWritable, Text, FieldIndexer.LuceneDocumentWrapper> {
+
+ public static final Log LOG = LogFactory.getLog(FieldIndexer.class);
+ public static final String DONE_NAME = "index.done";
+
+ private FieldFilters fieldFilters;
+
+ public static class LuceneDocumentWrapper
+ implements Writable {
+ private Document doc;
+
+ public LuceneDocumentWrapper(Document doc) {
+ this.doc = doc;
+ }
+
+ public Document get() {
+ return doc;
+ }
+
+ public void readFields(DataInput in)
+ throws IOException {
+ // intentionally left blank
+ }
+
+ public void write(DataOutput out)
+ throws IOException {
+ // intentionally left blank
+ }
+
+ }
+
+ public static class OutputFormat
+ extends FileOutputFormat<WritableComparable, LuceneDocumentWrapper> {
+
+ public RecordWriter<WritableComparable, LuceneDocumentWrapper> getRecordWriter(
+ final FileSystem fs, JobConf job, String name, final Progressable progress)
+ throws IOException {
+
+ final Path perm = new Path(FileOutputFormat.getOutputPath(job), name);
+ final Path temp = job.getLocalPath("index/_"
+ + Integer.toString(new Random().nextInt()));
+
+ fs.delete(perm, true); // delete old, if any
+
+ final AnalyzerFactory factory = new AnalyzerFactory(job);
+ final IndexWriter writer = // build locally first
+ new IndexWriter(fs.startLocalOutput(perm, temp).toString(),
+ new NutchDocumentAnalyzer(job), true);
+
+ writer.setMergeFactor(job.getInt("indexer.mergeFactor", 10));
+ writer.setMaxBufferedDocs(job.getInt("indexer.minMergeDocs", 100));
+ writer.setMaxMergeDocs(job.getInt("indexer.maxMergeDocs",
+ Integer.MAX_VALUE));
+ writer.setTermIndexInterval(job.getInt("indexer.termIndexInterval", 128));
+ writer.setMaxFieldLength(job.getInt("indexer.max.tokens", 10000));
+ writer.setInfoStream(LogUtil.getInfoStream(LOG));
+ writer.setUseCompoundFile(false);
+ writer.setSimilarity(new NutchSimilarity());
+
+ return new RecordWriter<WritableComparable, LuceneDocumentWrapper>() {
+ boolean closed;
+
+ public void write(WritableComparable key, LuceneDocumentWrapper value)
+ throws IOException { // unwrap & index doc
+ Document doc = value.get();
+ NutchAnalyzer analyzer = factory.get(doc.get("lang"));
+ if (LOG.isInfoEnabled()) {
+ LOG.info(" Indexing [" + doc.getField("url").stringValue() + "]"
+ + " with analyzer " + analyzer);
+ }
+ writer.addDocument(doc, analyzer);
+ progress.progress();
+ }
+
+ public void close(final Reporter reporter)
+ throws IOException {
+
+ // spawn a thread to give progress heartbeats
+ Thread prog = new Thread() {
+ public void run() {
+ while (!closed) {
+ try {
+ reporter.setStatus("closing");
+ Thread.sleep(1000);
+ }
+ catch (InterruptedException e) {
+ continue;
+ }
+ catch (Throwable e) {
+ return;
+ }
+ }
+ }
+ };
+
+ try {
+ prog.start();
+ if (LOG.isInfoEnabled()) {
+ LOG.info("Optimizing index.");
+ }
+ // optimize & close index
+ writer.optimize();
+ writer.close();
+ fs.completeLocalOutput(perm, temp); // copy to dfs
+ fs.createNewFile(new Path(perm, DONE_NAME));
+ }
+ finally {
+ closed = true;
+ }
+ }
+ };
+ }
+ }
+
+ public FieldIndexer() {
+
+ }
+
+ public FieldIndexer(Configuration conf) {
+ setConf(conf);
+ }
+
+ public void configure(JobConf job) {
+ setConf(job);
+ this.fieldFilters = new FieldFilters(job);
+ }
+
+ public void close() {
+ }
+
+ public void map(Text key, Writable value,
+ OutputCollector<Text, FieldWritable> output, Reporter reporter)
+ throws IOException {
+
+ if (value instanceof FieldsWritable) {
+ FieldsWritable fields = (FieldsWritable)value;
+ List<FieldWritable> fieldsList = fields.getFieldsList();
+ for (FieldWritable field : fieldsList) {
+ output.collect(key, field);
+ }
+ }
+ else if (value instanceof FieldWritable) {
+ output.collect(key, (FieldWritable)value);
+ }
+ }
+
+ public void reduce(Text key, Iterator<FieldWritable> values,
+ OutputCollector<Text, LuceneDocumentWrapper> output, Reporter reporter)
+ throws IOException {
+
+ Document doc = new Document();
+ List<FieldWritable> fieldsList = new ArrayList<FieldWritable>();
+ Configuration conf = getConf();
+
+ while (values.hasNext()) {
+ FieldWritable field = values.next();
+ fieldsList.add((FieldWritable)WritableUtils.clone(field, conf));
+ }
+
+ try {
+ doc = fieldFilters.filter(key.toString(), doc, fieldsList);
+ }
+ catch (IndexingException e) {
+ throw new IOException(e);
+ }
+
+ if (doc != null) {
+ output.collect(key, new LuceneDocumentWrapper(doc));
+ }
+ }
+
+ public void index(Path[] fields, Path indexDir)
+ throws IOException {
+
+ LOG.info("FieldIndexer: starting");
+
+ JobConf job = new NutchJob(getConf());
+ job.setJobName("FieldIndexer: " + indexDir);
+
+ for (int i = 0; i < fields.length; i++) {
+ Path fieldsDb = fields[i];
+ LOG.info("FieldIndexer: adding fields db: " + fieldsDb);
+ FileInputFormat.addInputPath(job, fieldsDb);
+ }
+
+ job.setInputFormat(SequenceFileInputFormat.class);
+ job.setMapperClass(FieldIndexer.class);
+ job.setReducerClass(FieldIndexer.class);
+ FileOutputFormat.setOutputPath(job, indexDir);
+ job.setOutputFormat(OutputFormat.class);
+ job.setMapOutputKeyClass(Text.class);
+ job.setMapOutputValueClass(FieldWritable.class);
+ job.setOutputKeyClass(Text.class);
+ job.setOutputValueClass(LuceneDocumentWrapper.class);
+
+ JobClient.runJob(job);
+ if (LOG.isInfoEnabled()) {
+ LOG.info("FieldIndexer: done");
+ }
+ }
+
+ public static void main(String[] args)
+ throws Exception {
+ int res = ToolRunner.run(NutchConfiguration.create(), new FieldIndexer(),
+ args);
+ System.exit(res);
+ }
+
+ public int run(String[] args)
+ throws Exception {
+
+ Options options = new Options();
+ Option helpOpts = OptionBuilder.withArgName("help").withDescription(
+ "show this help message").create("help");
+ Option outputOpts = OptionBuilder.withArgName("output").hasArg().withDescription(
+ "the output index directory").create("output");
+ Option fieldOpts = OptionBuilder.withArgName("fields").hasArgs().withDescription(
+ "the field database(s) to use").create("fields");
+ options.addOption(helpOpts);
+ options.addOption(fieldOpts);
+ options.addOption(outputOpts);
+
+ CommandLineParser parser = new GnuParser();
+ try {
+
+ CommandLine line = parser.parse(options, args);
+ if (line.hasOption("help") || !line.hasOption("fields")
+ || !line.hasOption("output")) {
+ HelpFormatter formatter = new HelpFormatter();
+ formatter.printHelp("FieldIndexer", options);
+ return -1;
+ }
+
+ Path output = new Path(line.getOptionValue("output"));
+ String[] fields = line.getOptionValues("fields");
+ Path[] fieldPaths = new Path[fields.length];
+ for (int i = 0; i < fields.length; i++) {
+ fieldPaths[i] = new Path(fields[i]);
+ }
+
+ index(fieldPaths, output);
+ return 0;
+ }
+ catch (Exception e) {
+ LOG.fatal("FieldIndexer: " + StringUtils.stringifyException(e));
+ return -2;
+ }
+ }
+}
diff --git a/src/java/org/apache/nutch/indexer/field/FieldType.java b/src/java/org/apache/nutch/indexer/field/FieldType.java
new file mode 100644
index 000000000..c4695ac87
--- /dev/null
+++ b/src/java/org/apache/nutch/indexer/field/FieldType.java
@@ -0,0 +1,14 @@
+package org.apache.nutch.indexer.field;
+
+/**
+ * The different types of fields. Different types of fields will be handled by
+ * different FieldFilter implementations during indexing.
+ */
+public enum FieldType {
+
+ CONTENT,
+ BOOST,
+ COMPUTATION,
+ ACTION;
+
+}
diff --git a/src/java/org/apache/nutch/indexer/field/FieldWritable.java b/src/java/org/apache/nutch/indexer/field/FieldWritable.java
new file mode 100644
index 000000000..8859d0d35
--- /dev/null
+++ b/src/java/org/apache/nutch/indexer/field/FieldWritable.java
@@ -0,0 +1,129 @@
+package org.apache.nutch.indexer.field;
+
+import java.io.DataInput;
+import java.io.DataOutput;
+import java.io.IOException;
+
+import org.apache.hadoop.io.Text;
+import org.apache.hadoop.io.Writable;
+
+/**
+ * A class that holds a single field of content to be placed into an index.
+ *
+ * This class has options type of content as well as for how the field is to
+ * be indexed.
+ */
+public class FieldWritable
+ implements Writable {
+
+ private String name;
+ private String value;
+ private FieldType type = FieldType.CONTENT;
+ private float boost;
+ private boolean indexed = true;
+ private boolean stored = false;
+ private boolean tokenized = true;
+
+ public FieldWritable() {
+
+ }
+
+ public FieldWritable(String name, String value, FieldType type, float boost) {
+ this(name, value, type, boost, true, false, true);
+ }
+
+ public FieldWritable(String name, String value, FieldType type,
+ boolean indexed, boolean stored, boolean tokenized) {
+ this(name, value, type, 0.0f, indexed, stored, tokenized);
+ }
+
+ public FieldWritable(String name, String value, FieldType type, float boost,
+ boolean indexed, boolean stored, boolean tokenized) {
+ this.name = name;
+ this.value = value;
+ this.type = type;
+ this.boost = boost;
+ this.indexed = indexed;
+ this.stored = stored;
+ this.tokenized = tokenized;
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public void setName(String name) {
+ this.name = name;
+ }
+
+ public String getValue() {
+ return value;
+ }
+
+ public void setValue(String value) {
+ this.value = value;
+ }
+
+ public FieldType getType() {
+ return type;
+ }
+
+ public void setType(FieldType type) {
+ this.type = type;
+ }
+
+ public float getBoost() {
+ return boost;
+ }
+
+ public void setBoost(float boost) {
+ this.boost = boost;
+ }
+
+ public boolean isIndexed() {
+ return indexed;
+ }
+
+ public void setIndexed(boolean indexed) {
+ this.indexed = indexed;
+ }
+
+ public boolean isStored() {
+ return stored;
+ }
+
+ public void setStored(boolean stored) {
+ this.stored = stored;
+ }
+
+ public boolean isTokenized() {
+ return tokenized;
+ }
+
+ public void setTokenized(boolean tokenized) {
+ this.tokenized = tokenized;
+ }
+
+ public void readFields(DataInput in)
+ throws IOException {
+ name = Text.readString(in);
+ value = Text.readString(in);
+ type = FieldType.valueOf(Text.readString(in));
+ boost = in.readFloat();
+ indexed = in.readBoolean();
+ stored = in.readBoolean();
+ tokenized = in.readBoolean();
+ }
+
+ public void write(DataOutput out)
+ throws IOException {
+ Text.writeString(out, name);
+ Text.writeString(out, value);
+ Text.writeString(out, type.toString());
+ out.writeFloat(boost);
+ out.writeBoolean(indexed);
+ out.writeBoolean(stored);
+ out.writeBoolean(tokenized);
+ }
+
+}
diff --git a/src/java/org/apache/nutch/indexer/field/Fields.java b/src/java/org/apache/nutch/indexer/field/Fields.java
new file mode 100644
index 000000000..8cf4a7d0f
--- /dev/null
+++ b/src/java/org/apache/nutch/indexer/field/Fields.java
@@ -0,0 +1,24 @@
+package org.apache.nutch.indexer.field;
+
+public interface Fields {
+
+ // names of common fields
+ public static final String ANCHOR = "anchor";
+ public static final String SEGMENT = "segment";
+ public static final String DIGEST = "digest";
+ public static final String HOST = "host";
+ public static final String SITE = "site";
+ public static final String URL = "url";
+ public static final String ORIG_URL = "orig";
+ public static final String SEG_URL = "segurl";
+ public static final String CONTENT = "content";
+ public static final String TITLE = "title";
+ public static final String CACHE = "cache";
+ public static final String TSTAMP = "tstamp";
+ public static final String BOOSTFACTOR = "boostfactor";
+
+ // special fields for indexer
+ public static final String BOOST = "boost";
+ public static final String COMPUTATION = "computation";
+ public static final String ACTION = "action";
+}
diff --git a/src/java/org/apache/nutch/indexer/field/FieldsWritable.java b/src/java/org/apache/nutch/indexer/field/FieldsWritable.java
new file mode 100644
index 000000000..346c69551
--- /dev/null
+++ b/src/java/org/apache/nutch/indexer/field/FieldsWritable.java
@@ -0,0 +1,79 @@
+package org.apache.nutch.indexer.field;
+
+import java.io.DataInput;
+import java.io.DataOutput;
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.List;
+
+import org.apache.hadoop.io.Writable;
+
+/**
+ * A class that holds a grouping of FieldWritable objects.
+ */
+public class FieldsWritable
+ implements Writable {
+
+ private List<FieldWritable> fieldsList = new ArrayList<FieldWritable>();
+
+ public FieldsWritable() {
+
+ }
+
+ public boolean hasField(String name) {
+ for (FieldWritable field : fieldsList) {
+ if (field.getName().equals(name)) {
+ return true;
+ }
+ }
+ return false;
+ }
+
+ public FieldWritable getField(String name) {
+ for (FieldWritable field : fieldsList) {
+ if (field.getName().equals(name)) {
+ return field;
+ }
+ }
+ return null;
+ }
+
+ public List<FieldWritable> getFields(String name) {
+ List<FieldWritable> named = new ArrayList<FieldWritable>();
+ for (FieldWritable field : fieldsList) {
+ if (field.getName().equals(name)) {
+ named.add(field);
+ }
+ }
+ return named.size() > 0 ? named : null;
+ }
+
+ public List<FieldWritable> getFieldsList() {
+ return fieldsList;
+ }
+
+ public void setFieldsList(List<FieldWritable> fieldsList) {
+ this.fieldsList = fieldsList;
+ }
+
+ public void readFields(DataInput in)
+ throws IOException {
+ fieldsList.clear();
+ int numFields = in.readInt();
+ for (int i = 0; i < numFields; i++) {
+ FieldWritable field = new FieldWritable();
+ field.readFields(in);
+ fieldsList.add(field);
+ }
+ }
+
+ public void write(DataOutput out)
+ throws IOException {
+ int numFields = fieldsList.size();
+ out.writeInt(numFields);
+ for (int i = 0; i < numFields; i++) {
+ fieldsList.get(i).write(out);
+ }
+ }
+
+}
diff --git a/src/plugin/build.xml b/src/plugin/build.xml
index 33e967ec5..93beec1e3 100755
--- a/src/plugin/build.xml
+++ b/src/plugin/build.xml
@@ -32,6 +32,8 @@
<ant dir="index-basic" target="deploy"/>
<ant dir="index-anchor" target="deploy"/>
<ant dir="index-more" target="deploy"/>
+ <ant dir="field-basic" target="deploy"/>
+ <ant dir="field-boost" target="deploy"/>
<ant dir="languageidentifier" target="deploy"/>
<ant dir="lib-http" target="deploy"/>
<ant dir="lib-jakarta-poi" target="deploy"/>
@@ -64,6 +66,7 @@
<ant dir="query-basic" target="deploy"/>
<ant dir="query-more" target="deploy"/>
<ant dir="query-site" target="deploy"/>
+ <ant dir="query-custom" target="deploy"/>
<ant dir="query-url" target="deploy"/>
<ant dir="scoring-opic" target="deploy"/>
<ant dir="scoring-link" target="deploy"/>
@@ -126,6 +129,8 @@
<ant dir="index-basic" target="clean"/>
<ant dir="index-anchor" target="clean"/>
<ant dir="index-more" target="clean"/>
+ <ant dir="field-basic" target="clean"/>
+ <ant dir="field-boost" target="clean"/>
<ant dir="languageidentifier" target="clean"/>
<ant dir="lib-commons-httpclient" target="clean"/>
<ant dir="lib-http" target="clean"/>
@@ -160,6 +165,7 @@
<ant dir="query-more" target="clean"/>
<ant dir="query-site" target="clean"/>
<ant dir="query-url" target="clean"/>
+ <ant dir="query-custom" target="clean"/>
<ant dir="scoring-opic" target="clean"/>
<ant dir="scoring-link" target="clean"/>
<ant dir="subcollection" target="clean"/>
diff --git a/src/plugin/field-basic/build.xml b/src/plugin/field-basic/build.xml
new file mode 100644
index 000000000..1b8ea02b7
--- /dev/null
+++ b/src/plugin/field-basic/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="field-basic" default="jar-core">
+
+ <import file="../build-plugin.xml"/>
+
+</project>
diff --git a/src/plugin/field-basic/plugin.xml b/src/plugin/field-basic/plugin.xml
new file mode 100644
index 000000000..3738178d8
--- /dev/null
+++ b/src/plugin/field-basic/plugin.xml
@@ -0,0 +1,41 @@
+<?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="field-basic"
+ name="Basic Field Filter"
+ version="1.0.0"
+ provider-name="nutch.org">
+
+ <runtime>
+ <library name="field-basic.jar">
+ <export name="*"/>
+ </library>
+ </runtime>
+
+ <requires>
+ <import plugin="nutch-extensionpoints"/>
+ </requires>
+
+ <extension id="org.apache.nutch.indexer.field.basic"
+ name="Nutch Basic Field Filter"
+ point="org.apache.nutch.indexer.field.FieldFilter">
+ <implementation id="BasicFieldFilter"
+ class="org.apache.nutch.indexer.field.basic.BasicFieldFilter"/>
+ </extension>
+
+</plugin>
diff --git a/src/plugin/field-basic/src/java/org/apache/nutch/indexer/field/basic/BasicFieldFilter.java b/src/plugin/field-basic/src/java/org/apache/nutch/indexer/field/basic/BasicFieldFilter.java
new file mode 100644
index 000000000..54a93958b
--- /dev/null
+++ b/src/plugin/field-basic/src/java/org/apache/nutch/indexer/field/basic/BasicFieldFilter.java
@@ -0,0 +1,89 @@
+package org.apache.nutch.indexer.field.basic;
+
+import java.util.List;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.apache.hadoop.conf.Configuration;
+import org.apache.lucene.document.Document;
+import org.apache.lucene.document.Field;
+import org.apache.nutch.indexer.IndexingException;
+import org.apache.nutch.indexer.field.FieldFilter;
+import org.apache.nutch.indexer.field.FieldType;
+import org.apache.nutch.indexer.field.FieldWritable;
+
+/**
+ * Adds any field of type content to the index.
+ */
+public class BasicFieldFilter
+ implements FieldFilter {
+
+ public static final Log LOG = LogFactory.getLog(BasicFieldFilter.class);
+ private Configuration conf;
+ private boolean supplemental = false;
+ private String[] suppFields = null;
+
+ private boolean isSupplementalField(String name) {
+ for (int i = 0; i < suppFields.length; i++) {
+ if (name != null && name.equals(suppFields[i])) {
+ return true;
+ }
+ }
+ return false;
+ }
+
+ public void setConf(Configuration conf) {
+ this.conf = conf;
+ this.supplemental = conf.getBoolean("index.supplemental", false);
+ String suppStr = conf.get("index.supplemental.fields", null);
+ if (suppStr != null) {
+ suppFields = suppStr.split(",");
+ }
+ }
+
+ public Configuration getConf() {
+ return this.conf;
+ }
+
+ public Document filter(String url, Document doc, List<FieldWritable> fields)
+ throws IndexingException {
+
+ // loop through all of the fields
+ for (FieldWritable field : fields) {
+
+ // only grab content fields
+ FieldType type = field.getType();
+ if (type == FieldType.CONTENT) {
+
+ String fieldName = field.getName();
+
+ // supplemental index will only index certain key fields, allow creating
+ // both a regular and a supplemental index
+ if (!supplemental || (supplemental && isSupplementalField(fieldName))) {
+
+ // create lucene fields from the FieldWritable objects
+ Field.Store store = field.isStored() ? Field.Store.YES
+ : Field.Store.NO;
+ Field.Index indexed = field.isIndexed() ? field.isTokenized()
+ ? Field.Index.TOKENIZED : Field.Index.UN_TOKENIZED : Field.Index.NO;
+ Field docField = new Field(fieldName, field.getValue(), store,
+ indexed);
+
+ // if any field boost then set it
+ float fieldBoost = field.getBoost();
+ if (fieldBoost > 0) {
+ docField.setBoost(fieldBoost);
+ }
+
+ // add the field to the lucene document
+ doc.add(docField);
+ }
+ else {
+ LOG.info("Ignoring " + fieldName + " field for " + url + " supplemental index");
+ }
+ }
+ }
+
+ return doc;
+ }
+}
diff --git a/src/plugin/field-boost/build.xml b/src/plugin/field-boost/build.xml
new file mode 100644
index 000000000..6c9434edc
--- /dev/null
+++ b/src/plugin/field-boost/build.xml
@@ -0,0 +1,40 @@
+<?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="field-boost" default="jar-core">
+
+ <import file="../build-plugin.xml"/>
+
+ <!-- Build compilation dependencies -->
+ <target name="deps-jar">
+ <ant target="jar" inheritall="false" dir="../lib-arity"/>
+ </target>
+
+ <!-- Add compilation dependencies to classpath -->
+ <path id="plugin.deps">
+ <fileset dir="${nutch.root}/build">
+ <include name="**/lib-arity/*.jar" />
+ </fileset>
+ </path>
+
+ <!-- Deploy Unit test dependencies -->
+ <target name="deps-test">
+ <ant target="deploy" inheritall="false" dir="../lib-arity"/>
+ <ant target="deploy" inheritall="false" dir="../nutch-extensionpoints"/>
+ </target>
+
+</project>
diff --git a/src/plugin/field-boost/plugin.xml b/src/plugin/field-boost/plugin.xml
new file mode 100644
index 000000000..f7bc4398f
--- /dev/null
+++ b/src/plugin/field-boost/plugin.xml
@@ -0,0 +1,41 @@
+<?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="field-boost"
+ name="Boost Field Filter"
+ version="1.0.0"
+ provider-name="nutch.org">
+
+ <runtime>
+ <library name="field-boost.jar">
+ <export name="*"/>
+ </library>
+ </runtime>
+
+ <requires>
+ <import plugin="nutch-extensionpoints"/>
+ </requires>
+
+ <extension id="org.apache.nutch.indexer.field.boost"
+ name="Nutch Boost Field Filter"
+ point="org.apache.nutch.indexer.field.FieldFilter">
+ <implementation id="BoostFieldFilter"
+ class="org.apache.nutch.indexer.field.boost.BoostFieldFilter"/>
+ </extension>
+
+</plugin>
diff --git a/src/plugin/field-boost/src/java/org/apache/nutch/indexer/field/boost/BoostFieldFilter.java b/src/plugin/field-boost/src/java/org/apache/nutch/indexer/field/boost/BoostFieldFilter.java
new file mode 100644
index 000000000..46d4efbcf
--- /dev/null
+++ b/src/plugin/field-boost/src/java/org/apache/nutch/indexer/field/boost/BoostFieldFilter.java
@@ -0,0 +1,68 @@
+package org.apache.nutch.indexer.field.boost;
+
+import java.util.ArrayList;
+import java.util.List;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.apache.hadoop.conf.Configuration;
+import org.apache.lucene.document.Document;
+import org.apache.lucene.document.Field;
+import org.apache.nutch.indexer.IndexingException;
+import org.apache.nutch.indexer.field.FieldFilter;
+import org.apache.nutch.indexer.field.FieldType;
+import org.apache.nutch.indexer.field.FieldWritable;
+import org.apache.nutch.indexer.field.Fields;
+
+/**
+ * A field filter that indexes fields of content type Boost or type Computation.
+ *
+ * Boost fields are aggregated together to create a global score for a single
+ * Lucene document in the index. An example of a Boost fields would be the
+ * LinkRank score.
+ */
+public class BoostFieldFilter
+ implements FieldFilter {
+
+ public static final Log LOG = LogFactory.getLog(BoostFieldFilter.class);
+ private Configuration conf;
+
+ public void setConf(Configuration conf) {
+ this.conf = conf;
+ }
+
+ public Configuration getConf() {
+ return this.conf;
+ }
+
+ public Document filter(String url, Document doc, List<FieldWritable> fields)
+ throws IndexingException {
+
+ List<String> comps = new ArrayList<String>();
+ float boost = 0.0f;
+
+ for (FieldWritable field : fields) {
+
+ // save the boost factor as unindexed fields, to show different scoring
+ FieldType type = field.getType();
+ if (type == FieldType.BOOST) {
+ float fieldBoost = field.getBoost();
+ boost += fieldBoost;
+ doc.add(new Field(Fields.BOOSTFACTOR, field.getValue() + ": "
+ + fieldBoost, Field.Store.YES, Field.Index.NO));
+ }
+ else if (type == FieldType.COMPUTATION) {
+ comps.add(field.getValue());
+ }
+ }
+
+ // set the boost for the document and save it in the index
+ doc.setBoost(boost);
+ doc.add(new Field(Fields.BOOST, Float.toString(boost), Field.Store.YES,
+ Field.Index.NO));
+
+
+ return doc;
+ }
+
+}
diff --git a/src/plugin/nutch-extensionpoints/plugin.xml b/src/plugin/nutch-extensionpoints/plugin.xml
index 6dfca56db..39c330301 100644
--- a/src/plugin/nutch-extensionpoints/plugin.xml
+++ b/src/plugin/nutch-extensionpoints/plugin.xml
@@ -28,6 +28,10 @@
id="org.apache.nutch.clustering.OnlineClusterer"
name="Nutch Online Search Results Clustering Plugin"/>
+<extension-point
+ id="org.apache.nutch.indexer.field.FieldFilter"
+ name="Nutch Field Filter"/>
+
<extension-point
id="org.apache.nutch.indexer.IndexingFilter"
name="Nutch Indexing Filter"/>
diff --git a/src/plugin/query-custom/build.xml b/src/plugin/query-custom/build.xml
new file mode 100644
index 000000000..f003d29c8
--- /dev/null
+++ b/src/plugin/query-custom/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="query-custom" default="jar-core">
+
+ <import file="../build-plugin.xml"/>
+
+</project>
diff --git a/src/plugin/query-custom/plugin.xml b/src/plugin/query-custom/plugin.xml
new file mode 100644
index 000000000..e1e414dc8
--- /dev/null
+++ b/src/plugin/query-custom/plugin.xml
@@ -0,0 +1,44 @@
+<?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="query-custom"
+ name="Custom Query Filter"
+ version="1.0.0"
+ provider-name="nutch.org">
+
+ <runtime>
+ <library name="query-custom.jar">
+ <export name="*"/>
+ </library>
+ </runtime>
+
+ <requires>
+ <import plugin="nutch-extensionpoints"/>
+ </requires>
+
+ <extension id="org.apache.nutch.searcher.custom"
+ name="Nutch Custom Field Query Filter"
+ point="org.apache.nutch.searcher.QueryFilter">
+ <implementation id="CustomQueryFilter"
+ class="org.apache.nutch.searcher.custom.CustomFieldQueryFilter">
+ <parameter name="fields" value="lang" />
+ </implementation>
+
+ </extension>
+
+</plugin>
diff --git a/src/plugin/query-custom/src/java/org/apache/nutch/searcher/custom/CustomFieldQueryFilter.java b/src/plugin/query-custom/src/java/org/apache/nutch/searcher/custom/CustomFieldQueryFilter.java
new file mode 100644
index 000000000..2e6d14308
--- /dev/null
+++ b/src/plugin/query-custom/src/java/org/apache/nutch/searcher/custom/CustomFieldQueryFilter.java
@@ -0,0 +1,125 @@
+package org.apache.nutch.searcher.custom;
+
+/**
+ * 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.
+ */
+
+import java.io.IOException;
+import java.io.InputStream;
+import java.util.ArrayList;
+import java.util.Enumeration;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Properties;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.apache.hadoop.conf.Configuration;
+import org.apache.hadoop.fs.FileSystem;
+import org.apache.hadoop.util.StringUtils;
+import org.apache.lucene.index.Term;
+import org.apache.lucene.search.BooleanClause;
+import org.apache.lucene.search.BooleanQuery;
+import org.apache.lucene.search.TermQuery;
+import org.apache.nutch.indexer.field.CustomFields;
+import org.apache.nutch.searcher.Query;
+import org.apache.nutch.searcher.QueryException;
+import org.apache.nutch.searcher.QueryFilter;
+import org.apache.nutch.searcher.Query.Clause;
+
+public class CustomFieldQueryFilter
+ implements QueryFilter {
+
+ public static final Log LOG = LogFactory.getLog(CustomFields.class);
+ private Configuration conf;
+ private List<String> fieldNames = new ArrayList<String>();
+ private Map<String, Float> boosts = new HashMap<String, Float>();
+
+ public CustomFieldQueryFilter() {
+ }
+
+ public void setConf(Configuration conf) {
+
+ try {
+ this.conf = conf;
+ FileSystem fs = FileSystem.get(conf);
+ String configFile = conf.get("custom.fields.config", "custom-fields.xml");
+ LOG.info("Reading configuration field configuration from " + configFile);
+ Properties customFieldProps = new Properties();
+ InputStream fis = CustomFields.class.getClassLoader().getResourceAsStream(
+ configFile);
+ if (fis == null) {
+ throw new IOException("Was unable to open " + configFile);
+ }
+ customFieldProps.loadFromXML(fis);
+ Enumeration keys = customFieldProps.keys();
+ while (keys.hasMoreElements()) {
+ String prop = (String)keys.nextElement();
+ if (prop.endsWith(".name")) {
+ String propName = prop.substring(0, prop.length() - 5);
+ String name = customFieldProps.getProperty(prop);
+ fieldNames.add(name);
+ String boostKey = propName + ".boost";
+ if (customFieldProps.containsKey(boostKey)) {
+ float boost = Float.parseFloat(customFieldProps.getProperty(boostKey));
+ boosts.put(name, boost);
+ }
+ }
+ }
+ }
+ catch (Exception e) {
+ LOG.error("Error loading custom field properties:\n"
+ + StringUtils.stringifyException(e));
+ }
+ }
+
+ public Configuration getConf() {
+ return this.conf;
+ }
+
+ public BooleanQuery filter(Query input, BooleanQuery output)
+ throws QueryException {
+
+ // examine each clause in the Nutch query
+ Clause[] clauses = input.getClauses();
+ for (int i = 0; i < clauses.length; i++) {
+ Clause c = clauses[i];
+
+ // skip non-matching clauses
+ String fieldName = c.getField();
+ if (!fieldNames.contains(fieldName)) {
+ continue;
+ }
+ String value = c.getTerm().toString().toLowerCase();
+
+ // add a Lucene TermQuery for this clause
+ TermQuery clause = new TermQuery(new Term(fieldName, value));
+ // set boost
+ if (boosts.containsKey(fieldName)) {
+ clause.setBoost(boosts.get(fieldName));
+ }
+
+ // add it as specified in query
+ output.add(clause, (c.isProhibited() ? BooleanClause.Occur.MUST_NOT
+ : (c.isRequired() ? BooleanClause.Occur.MUST
+ : BooleanClause.Occur.SHOULD)));
+ }
+
+ // return the modified Lucene query
+ return output;
+ }
+}