Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Understanding Information Retrieval by Using Apache Lucene and Tika - Part 1

DZone's Guide to

Understanding Information Retrieval by Using Apache Lucene and Tika - Part 1

· Big Data Zone
Free Resource

Access NoSQL and Big Data through SQL using standard drivers (ODBC, JDBC, ADO.NET). Free Download 

Introduction

In this tutorial, the Apache Lucene and Apache Tika frameworks will  be explained through their core concepts (e.g.  parsing, mime detection,  content analysis, indexing,  scoring, boosting) via illustrative examples that should be applicable to not only seasoned software developers but to beginners to content analysis and programming as well. We assume you have a working knowledge of the Java™ programming language and plenty of content to analyze.

Throughout this tutorial, you will learn:

  • how to use Apache Tika's API and its most relevant functions
  • how to develop code with Apache Lucene API and its most important modules
  • how to integrate Apache Lucene and Apache Tika in order to build your own piece of software that stores and retrieves information efficiently. (project code is available for download)

 What are Lucene and Tika?

  According to Apache Lucene's site, Apache Lucene represents an open source Java library for indexing and searching from within large collections of documents. The index size represents roughly 20-30% the size of text indexed and the search algorithms provide features like:

  • ranked searching - best results returned first
  • many powerful query types: phrase queries, wildcard queries, proximity queries, range queries and more. In this tutorial we will demonstrate only phrase queries.
  • fielded search (e.g. title, author, contents)
  • sorting by any field
  • flexible faceting, highlighting, joins and result grouping
  • pluggable ranking models, including the Vector Space Model and Okapi BM25

  But Lucene's main purpose is to deal directly with text and we want to manipulate documents, who have various formats and encoding. For parsing document content and their properties the Apache Tika library it is necessary.

  Apache Tika is a library that provides a flexible and robust set of interfaces that can be used in any context where metadata analyzis and structured text extraction is needed. The key component of Apache Tika is the Parser (org.apache.tika.parser.Parser ) interface because  it hides the complexity of different file formats  while providing a simple and powerful mechanism  to extract structured text content and metadata from all sorts of documents.

Criterias for Tika parsing design

Streamed parsing

The interface should require neither the client application nor the parser implementation to keep the full document content in memory or spooled to disk. This allows even huge documents to be parsed without excessive resource requirements.

Structured content

A parser implementation should be able to include structural information (headings, links, etc.) in the extracted content. A client application can use this information for example to better judge the relevance of different parts of the parsed document.

Input metadata

A client application should be able to include metadata like the file name or declared content type with the document to be parsed. The parser implementation can use this information to better guide the parsing process.

Output metadata

A parser implementation should be able to return document metadata in addition to document content. Many document formats contain metadata like the name of the author that may be useful to client applications.

Context sensitivity

While the default settings and behaviour of Tika parsers should work well for most use cases, there are still situations where more fine-grained control over the parsing process is desirable. It should be easy to inject such context-specific information to the parsing process without breaking the layers of abstraction.


Requirements

  • Maven  2.0 or higher
  • Java 1.6 SE or higher

Lesson 1: Automate metadata extraction from any file type

Our premisses are the following: we have a collection of documents stored on disk/database and we would like to index them; these documents can be Word Documents, PDFs, HTMLs, plain text files etc. As we are developers, we would like to write reusable code that extracts file properties regarding format (metadata) and file content.  Apache Tika has a mimetype repository and a set of schemes (any combination of mime MAGIC, URL patterns, XML root characters, or file extensions) to determine if a particular file, URL, or piece of content matches one of its known types. If the content does match, Tika has detected its mimetype and can proceed to select the appropriate parser.

  In the sample code, the file type detection and its parsing is being covered inside the class com.retriever.lucene.index.IndexCreator, method indexFile.

Listing 1.1 Analyzing a File with Tika

public static DocumentWithAbstract indexFile(Analyzer analyzer, File file) throws IOException {
        Metadata metadata = new Metadata();
        ContentHandler handler = new BodyContentHandler(10 * 1024 * 1024);
        ParseContext context = new ParseContext();
        Parser parser = new AutoDetectParser();
        InputStream stream = new FileInputStream(file); //open stream
        try {
            parser.parse(stream, handler, metadata, context); //parse the stream 
        } catch (TikaException e) {
            e.printStackTrace();
        } catch (SAXException e) {
            e.printStackTrace();
        } finally {
            stream.close(); //close the stream
        }
   //more code here 
 }

The above code displays how a File it is being parsed using org.apache.tika.parser.AutoDetectParser;  this kind of implementation was chosen because we would like to achieve parsing documents disregarding their format.  Also, for handling the content the org.apache.tika.sax.BodyContentHandler wasconstructed with a writeLimit given as parameter ( 10*1024*1024); this type of constructor creates a content handler that writes XHTML body character events to an internal string buffer and in case of documents with large content is less likely to throw a SAXException (thrown when the default write limit is reached). 

As a result of our parsing we have obtained a metadata object that we can now use to detect file properties (title or any other header specific to a document format). Metadata processing can be done as described below (com.retriever.lucene.index.IndexCreator, method indexFileDescriptors) :

  Listing 1.2 Processing metadata

private static Document indexFileDescriptors(String fileName, Metadata metadata) {
        Document doc = new Document();
        //store file name in a separate TextField
        doc.add(new TextField(ISearchConstants.FIELD_FILE, fileName, Store.YES)); 
        
        for (String key : metadata.names()) {
            String name = key.toLowerCase();
            String value = metadata.get(key);

            if (StringUtils.isBlank(value)) {
                continue;
            }

            if ("keywords".equalsIgnoreCase(key)) {
                for (String keyword : value.split(",?(\\s+)")) {
                    doc.add(new TextField(name, keyword, Store.YES));
                }
            } else if (ISearchConstants.FIELD_TITLE.equalsIgnoreCase(key)) {
                doc.add(new TextField(name, value, Store.YES));
            } else {
                doc.add(new TextField(name, fileName, Store.NO));
            }
        }

In the method presented above we store the file name in a separate field and also the document's title ( a document can have a title different from its file name);  we are not interested in storing other  informations.

The fastest databases need the fastest drivers - learn how you can leverage CData Drivers for high performance NoSQL & Big Data Access.

Topics:

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}