Remove SearchBean - it has been deprecated by the sorting feature in Lucene 1.4

git-svn-id: https://svn.apache.org/repos/asf/lucene/java/trunk@153427 13f79535-47bb-0310-9956-ffa450edef68
This commit is contained in:
Erik Hatcher 2005-02-11 18:07:20 +00:00
parent f375d09898
commit 6d5d317091
8 changed files with 0 additions and 799 deletions

View File

@ -1,10 +0,0 @@
<?xml version="1.0"?>
<project name="searchbean" default="default">
<description>
SearchBean
</description>
<import file="../common.xml"/>
</project>

View File

@ -1,20 +0,0 @@
package org.apache.lucene.beans;
import org.apache.lucene.beans.IndividualHit;
public class CompareDocumentsByField implements java.util.Comparator {
public int compare(Object hit1, Object hit2) {
String myDate1 = ((IndividualHit) hit1).getField();
String myDate2 = ((IndividualHit) hit2).getField();
if ((myDate1 == null) || (myDate2 == null)) {
//logger.error("A date was null, the score is "+((IndividualHit) hit1).getScore());
//return -1;
}
return -1 * (myDate1.compareTo(myDate2)); //sort in descending order
}
public boolean equals(Object o1) {
return false;
}
}

View File

@ -1,227 +0,0 @@
/*
* HitsIterator.java
* Provides an Iterator class around Lucene Hits
* It also supports paging
* Created on November 1, 2001, 8:53 PM
*/
package org.apache.lucene.beans;
import org.apache.lucene.beans.SortedField;
import org.apache.lucene.beans.CompareDocumentsByField;
import org.apache.lucene.document.Document;
import org.apache.lucene.search.Hits;
import java.io.IOException;
import java.util.Arrays;
import java.util.Comparator;
//import org.apache.log4j.Logger;
/**
*
* @author Peter Carlson
* @version 1.0
*/
public class HitsIterator {
//static Logger logger = Logger.getLogger(HitsIterator.class.getName());
private int currentPosition = 0;
private Hits hitsCollection = null;
private Object[] arrayOfIndividualHits = null;
private int totalHits = 0;
private int pageSize = 25; // default page size
private int currentPage = 1; // range from 1 to totalHits%pageSize
private int totalPages = -1; // set by constructor
private int endPagePosition = 0; // position currentPage ends
/** Creates new HitsIterator */
private HitsIterator() {
}
public HitsIterator(Hits hits) throws IOException{
this(hits,null);
}
public HitsIterator(Hits hits, String sortFlag) throws IOException{
this.hitsCollection = hits;
if (sortFlag != null){
if (sortFlag != "") {
System.out.println("Sorting hits by field "+sortFlag);
sortByField(sortFlag);
//logger.debug("Completed sorting by field "+sortFlag);
}
}
totalHits = getTotalHits();
setPageCount();
}
/** sorts hits by the given sort flag
* fills an interal array
* @param sortFlag field to sort results on
*/
private void sortByField(String fieldName) throws IOException{
long start = System.currentTimeMillis();
Comparator c = null;
if (fieldName == null){
//logger.error("sort field is null");
return;
}
SortedField sf = SortedField.getSortedField(fieldName);
if (sf !=null){
c = (Comparator) new CompareDocumentsByField();
} else {
//logger.error("Sort field not found");
// use default sort of Lucene -- Relevance
// Should I throw an exception here?
arrayOfIndividualHits = null;
return;
}
arrayOfIndividualHits = new Object[hitsCollection.length()];
long first = System.currentTimeMillis();
for (int i=0; i<hitsCollection.length(); i++) {
int id = hitsCollection.id(i);
arrayOfIndividualHits[i] = new IndividualHit(i, sf.getFieldValue(id), hitsCollection.score(i));
}
long second = System.currentTimeMillis();
//logger.debug("HitsIterator.sortByField(): filling Obj[] took "+(second-first));
Arrays.sort(arrayOfIndividualHits, c);
//logger.debug("HitsIterator.sortByField(): sort took "+(System.currentTimeMillis()-second));
}
private void setPageCount() {
if (totalHits == 0){
totalPages = 0;
setCurrentPage(0);
} else {
totalPages = totalHits / pageSize;
//account for remainder if not exaxtly divisable
if (totalHits % pageSize != 0)
{ totalPages++;}
setCurrentPage(1); // reset currentPage to make sure not over the limit
}
}
public int getPageCount() {
return totalPages;
}
public org.apache.lucene.document.Document setPosition(int position) throws IOException{
if (position > totalHits) {
return null;
}
currentPosition = position;
return getDoc();
}
public org.apache.lucene.document.Document next() throws IOException{
currentPosition++;
if (currentPosition > totalHits) {
currentPosition = totalHits;
return null ;
}
return getDoc();
}
public org.apache.lucene.document.Document previous() throws IOException{
currentPosition--;
if (currentPosition < 0)
{ return null;}
return getDoc();
}
public boolean hasNext() {
if (currentPosition < endPagePosition)
{ return true; }
return false;
}
public org.apache.lucene.document.Document getDoc() throws IOException {
// Determine if using relevnace or sorting by another field
if (arrayOfIndividualHits == null)
return hitsCollection.doc(currentPosition - 1);
else {
int i = ((IndividualHit)arrayOfIndividualHits[currentPosition - 1]).getIndex();
return hitsCollection.doc(i);
}
}
public int getScore() throws Exception{
// Determine if using relevnace or sorting by another field
if (arrayOfIndividualHits == null)
return (int) (hitsCollection.score(currentPosition - 1)*100.0f);
else
return (int) (((IndividualHit)arrayOfIndividualHits[currentPosition - 1]).getScore()*100.0f);
}
public int getTotalHits() {
return hitsCollection.length();
}
public int getCurrentPosition() {
return currentPosition;
}
public int getPageSize() {
return pageSize;
}
public void setPageSize(int pageSize) {
this.pageSize = pageSize;
setPageCount();
}
public void setCurrentPage(int currentPage) throws IndexOutOfBoundsException{
if (currentPage > totalPages){
currentPage = totalPages; // don't allow to go over max
//throw new IndexOutOfBoundsException("currentPage greater than total pages");
}
this.currentPage = currentPage;
currentPosition = ((currentPage - 1) * pageSize);
endPagePosition = Math.min( ((currentPage - 1)*pageSize) + pageSize, totalHits);
}
public int getCurrentPage() {
return currentPage;
}
/**
* set page number to next page, unless last page, then
* always return last page number
*@return current page number
*/
public int nextPage() {
setCurrentPage(currentPage++);
return getCurrentPage();
}
/**
* set page number to previous page, unless first page,
* then always return first page number
*@return current page number
*/
public int previousPage() {
setCurrentPage(currentPage--);
return getCurrentPage();
}
}

View File

@ -1,36 +0,0 @@
package org.apache.lucene.beans;
import org.apache.lucene.document.Document;
public class IndividualHit
{
private float score;
private String field;
private int index;
private IndividualHit()
{
}
public IndividualHit(int inIndex, String field, float inScore)
{
this.index = inIndex;
this.field = field;
this.score = inScore;
}
public int getIndex()
{
return this.index;
}
public String getField()
{
return this.field;
}
public float getScore()
{
return this.score;
}
}

View File

@ -1,49 +0,0 @@
package org.apache.lucene.beans;
import java.util.Iterator;
import java.io.IOException;
/**
* Acts as an adapter for HitsIterator to comply with the Collections
* API.
*
* @author <a href="mailto:kelvint@apache.org">Kelvin Tan</a>
* @version $Id$
*/
public final class IteratorAdapter implements Iterator
{
private HitsIterator hitsIterator;
public IteratorAdapter(HitsIterator it)
{
this.hitsIterator = it;
}
public boolean hasNext()
{
return hitsIterator.hasNext();
}
public Object next()
{
Object obj = null;
try {
obj = hitsIterator.next();
} catch (IOException e) {
// ignore for now, returning null might be good enough?
}
return obj;
}
public void remove()
{
throw new UnsupportedOperationException(
"HitsIterator does not " +
"support modification of the hits!");
}
public HitsIterator getHitsIterator()
{
return hitsIterator;
}
}

View File

@ -1,223 +0,0 @@
/*
* SearchBean.java
*
* Created on November 1, 2001, 10:31 AM
*/
package org.apache.lucene.beans;
import org.apache.lucene.search.Searcher;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.Hits;
import org.apache.lucene.store.Directory;
import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.analysis.standard.StandardAnalyzer;
import org.apache.lucene.queryParser.QueryParser;
import org.apache.lucene.queryParser.ParseException;
import org.apache.lucene.beans.HitsIterator;
import java.io.IOException;
//import org.apache.log4j.Logger;
/**
*
* @author peter carlson
* @version 1.0
*/
public class SearchBean extends Object {
static final String SORT_FIELD_RELEVANCE = "relevance";
private String queryString = "";
private String querySortField = SORT_FIELD_RELEVANCE; // default
private String queryType = "";
private Directory directory;
private HitsIterator hitsIterator = null;
private String defaultSearchField = "text";
private long searchTime = 0;
private Searcher searcher = null;
// static Logger logger = Logger.getLogger(SearchBean.class.getName());
// static Logger searchLogger = Logger.getLogger("searchLog");
/** Creates new SearchBean
*/
public SearchBean(Directory directory) {
this.directory = directory;
}
/** Creates new SearchBean
* @param directory index
* @param queryString string to search with
*/
public SearchBean(Directory directory, String queryString) {
this(directory);
setQueryString(queryString);
}
/** Creates new SearchBean
* @param directory index
* @param queryString string to search with
* @param querySortField field to sort on
*/
public SearchBean(Directory directory, String queryString, String querySortField) {
this(directory);
setQueryString(queryString);
setQuerySortField(querySortField);
}
/** Creates new SearchBean
* @param directory index
* @param queryString string to search with
* @param querySortField field to sort on
* @param queryType used to indicate which index and default Field
*/
public SearchBean(Directory directory, String queryString, String querySortField, String queryType){
this(directory);
setQueryString(queryString);
setQuerySortField(querySortField);
setQueryType(queryType);
}
/** main search method
*/
public HitsIterator search() throws IOException, ParseException{
return search(queryString,querySortField);
}
/** main search method
* @param queryString string to search with
*/
public HitsIterator search(String queryString) throws IOException, ParseException{
return search(queryString,queryString);
}
/** main search method
* @param queryString string to search with
* @param querySortField field to sort on
*/
public HitsIterator search(String queryString, String querySortField) throws IOException, ParseException{
return search(queryString, querySortField, queryType);
}
/** main search method
* @param queryString string to search with
* @param querySortField field to sort on
* @param queryType used to indicate the index to search
*/
public HitsIterator search(String queryString, String querySortField, String queryType) throws IOException, ParseException {
long startTime = System.currentTimeMillis();
Hits hits = searchHits(queryString, queryType);
//if (hits == null) {return null;}
//if (hits.length() == 0) {return null;}
HitsIterator hi = new HitsIterator(hits, querySortField);
long endTime = System.currentTimeMillis();
setSearchTime(endTime - startTime);
setHitsIterator(hi);
//searchLogger.info("queryString = "+queryString + "sort field = "+ querySortField +" #results = "+hits.length());
return hi;
}
/** does the actual searching
*/
private Hits searchHits(String queryString, String queryType) throws IOException, ParseException{
System.out.println("queryString = " + queryString);
if (queryString == "") {
return null;
}
// Provide for multiple indices in the future
searcher = new IndexSearcher(directory);
Query query = getQuery(queryString, defaultSearchField);
System.out.println("###querystring= "+query.toString(defaultSearchField));
Hits hits = searcher.search(query);
//System.out.println("Number hits = "+hits.length());
//logger.debug("queryString = "+query.toString(searchField)+" hits = "+hits.length()+" queryType = "+queryType+" indexPath = "+indexPath );
return hits;
}
/**
* frees resources associated with SearchBean search
*/
public void close() throws IOException{
searcher.close();
}
/** <queryString> | <queryType> | <querySortField>
*/
public String toString(){
return queryString+"|"+queryType+"|"+querySortField;
}
public void setQueryString(String queryString) {
this.queryString = queryString;
}
public String getQueryString(){
return queryString;
}
/** Parses the query
* @todo allow for user defined analyzer
*/
private Query getQuery(String queryString, String searchField) throws ParseException {
//String defaultSearchField = "text";
Analyzer analyzer = new StandardAnalyzer();
Query query = QueryParser.parse(queryString, searchField, analyzer);
//System.out.println(query.toString());
return query;
}
public String getDefaultSearchField() {
return defaultSearchField;
}
public void setDefaultSearchField(String defaultSearchField) {
this.defaultSearchField = defaultSearchField;
}
public long getSearchTime() {
return searchTime;
}
public void setSearchTime(long searchTime) {
this.searchTime = searchTime;
}
public java.lang.String getQuerySortField() {
return querySortField;
}
public void setQuerySortField(String querySortField) {
this.querySortField = querySortField;
}
public HitsIterator getHitsIterator() {
return hitsIterator;
}
public void setHitsIterator(HitsIterator hitsIterator) {
this.hitsIterator = hitsIterator;
}
public String getQueryType() {
return queryType;
}
public void setQueryType(String queryType) {
this.queryType = queryType;
}
public Directory getDirectory() {
return directory;
}
public void setDirectory(Directory directory) {
this.directory = directory;
}
}

View File

@ -1,108 +0,0 @@
/*
* SortedField.java
*
* Created on May 20, 2002, 4:15 PM
*/
package org.apache.lucene.beans;
import org.apache.lucene.index.IndexReader;
import org.apache.lucene.store.Directory;
import java.util.Hashtable;
import java.io.File;
import java.io.IOException;
/**
*
* @author carlson
*/
public class SortedField {
private String fieldName;
private String[] fieldValues;
private static Hashtable fieldList = new Hashtable(); //keeps track of all fields
/** Creates a new instance of SortedField */
private SortedField(String fieldName) {
this.fieldName = fieldName;
}
/** add a field so that is can be used to sort
* @param fieldName the name of the field to add
* @param indexPath path to Lucene index directory
*/
public static void addField(String fieldName, String indexPath) throws IOException{
IndexReader ir = IndexReader.open(indexPath);
addField(fieldName, ir);
}
/** add a field so that is can be used to sort
* @param fieldName the name of the field to add
* @param indexFile File pointing to Lucene index directory
*/
public static void addField(String fieldName, File indexFile) throws IOException{
IndexReader ir = IndexReader.open(indexFile);
addField(fieldName, ir);
}
/** add a field so that is can be used to sort
* @param fieldName the name of the field to add
* @param directory Lucene Directory
*/
public static void addField(String fieldName, Directory directory) throws IOException{
IndexReader ir = IndexReader.open(directory);
addField(fieldName, ir);
}
private static void addField(String fieldName, IndexReader ir) throws IOException{
SortedField sortedField = new SortedField(fieldName);
sortedField.addSortedField(fieldName,ir);
//long start = System.currentTimeMillis();
fieldList.put(fieldName, sortedField);
//logger.info("adding data from field "+fieldName+" took "+(System.currentTimeMillis()-start));
}
/** adds the data from the index into a string array
*/
private void addSortedField(String fieldName, IndexReader ir) throws IOException{
int numDocs = ir.numDocs();
fieldValues = new String[numDocs];
for (int i=0; i<numDocs; i++) {
if (ir.isDeleted(i) == false){
fieldValues[i] = ir.document(i).get(fieldName);
} else {
fieldValues[i] = "";
}
}
ir.close();
}
/** returns the value of the field
* @param globalID Lucene's global document ID
* @return value of field
*/
public String getFieldValue(int globalID) {
return fieldValues[globalID];
}
/** provides way to retrieve a SortedField once you add it
* @param fieldName name of field to lookup
* @return SortedField field to use when sorting
*/
public static SortedField getSortedField(String fieldName){
return (SortedField) fieldList.get(fieldName);
}
/** Getter for property fieldName.
* @return Value of property fieldName.
*/
public java.lang.String getFieldName() {
return fieldName;
}
}

View File

@ -1,126 +0,0 @@
package org.apache.lucene;
/* ====================================================================
* The Apache Software License, Version 1.1
*
* Copyright (c) 2001 The Apache Software Foundation. All rights
* reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. The end-user documentation included with the redistribution,
* if any, must include the following acknowledgment:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowledgment may appear in the software itself,
* if and wherever such third-party acknowledgments normally appear.
*
* 4. The names "Apache" and "Apache Software Foundation" and
* "Apache Lucene" must not be used to endorse or promote products
* derived from this software without prior written permission. For
* written permission, please contact apache@apache.org.
*
* 5. Products derived from this software may not be called "Apache",
* "Apache Lucene", nor may "Apache" appear in their name, without
* prior written permission of the Apache Software Foundation.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
* USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*/
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.store.RAMDirectory;
import org.apache.lucene.store.Directory;
import org.apache.lucene.analysis.standard.StandardAnalyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.apache.lucene.index.IndexReader;
import org.apache.lucene.queryParser.ParseException;
import org.apache.lucene.beans.SearchBean;
import org.apache.lucene.beans.HitsIterator;
import org.apache.lucene.beans.SortedField;
import junit.framework.TestCase;
import java.io.IOException;
public class TestSearchBean extends TestCase{
public void testSearchBean() throws IOException, ParseException {
Directory indexStore = createIndex();
SortedField.addField("text",indexStore);
//IndexSearcher searcher = new IndexSearcher(indexStore);
SearchBean sb = new SearchBean(indexStore);
HitsIterator hi = sb.search("metal");
assertEquals(1, hi.getTotalHits());
assertEquals(1, hi.getPageCount());
assertEquals("metal",hi.next().get("text"));
}
public void testUnoptimizedSearchBean() throws IOException, ParseException {
Directory indexStore = createIndex();
IndexReader reader = IndexReader.open(indexStore);
reader.delete(0);
//
reader.close();
SortedField.addField("text",indexStore);
//IndexSearcher searcher = new IndexSearcher(indexStore);
SearchBean sb = new SearchBean(indexStore);
HitsIterator hi = sb.search("metal");
assertEquals(0, hi.getTotalHits());
assertEquals(0, hi.getPageCount());
//assertEquals("metal",hi.next().get("text"));
}
public Directory createIndex() throws IOException{
RAMDirectory indexStore = new RAMDirectory();
IndexWriter writer = new IndexWriter(indexStore, new StandardAnalyzer(), true);
Document doc1 = new Document();
Document doc2 = new Document();
doc1.add(Field.Text("text", "metal"));
doc2.add(Field.Text("text", "metals"));
writer.addDocument(doc1);
writer.addDocument(doc2);
writer.optimize();
writer.close();
return indexStore;
}
}