I am implementing an autocomplete using lucene AnalyzingSuggerter API.
I have a data class as below
class Student implements java.io.Serializable {
int id;
String fullName;
String description;
public Student(int id, String fullName, String description) {
this.id = id;
this.description = description;
this.fullName = fullName;
}
}
I have implemented the iterator as follows
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.io.UnsupportedEncodingException;
import java.util.Comparator;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
import org.apache.lucene.search.suggest.InputIterator;
import org.apache.lucene.util.BytesRef;
class CourseIterator implements InputIterator
{
private Iterator<Course> courseIterator;
private Course currentCourse;
CourseIterator(Iterator<Course> courseIterator) {
this.courseIterator = courseIterator;
}
public boolean hasContexts() {
return false;
}
public boolean hasPayloads() {
return true;
}
public Comparator<BytesRef> getComparator() {
return null;
}
public BytesRef next() {
if (courseIterator.hasNext()) {
currentCourse = courseIterator.next();
try {
return new BytesRef(currentCourse.fullName.getBytes("UTF8"));
} catch (UnsupportedEncodingException e) {
throw new Error("Couldn't convert to UTF-8");
}
} else {
return null;
}
}
// payload is a serialized Java object representing our course.
public BytesRef payload() {
try {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
ObjectOutputStream out = new ObjectOutputStream(bos);
out.writeObject(currentCourse);
out.close();
return new BytesRef(bos.toByteArray());
} catch (IOException e) {
throw new Error("Well that's unfortunate.");
}
}
public Set<BytesRef> contexts() {
throw new Error("Unsupported Operation");
}
public long weight() {
return 1;
}
}
This works fine for data
new Student(1, "Elizabeth Smith", "test1");
new Student(2, "Will Smith", "test2");
new Student(3, "Smith Brown", "test3");
new Student(4, "Queen Elizabeth", "test4");
new Student(5, "Elena sam", "test1");
on auto suggestion search for
Eliz --> [1]
Smit --> [3]
El --> [1, 5]
Que --> [4]
I also wanted to taken the last name part of the fullname into account for autosearch therefore the result should be were lastname was taken into account and has less weight.
Eliz --> [1, 4]
Smit --> [3, 2]
El --> [1, 5, 4]
Que --> [4]
Can anyone suggest how to achive this?