Autocomplete server-side implementation

后端 未结 10 675
感动是毒
感动是毒 2020-12-28 16:03

What is a fast and efficient way to implement the server-side component for an autocomplete feature in an html input box?

I am writing a service to autocomplete use

10条回答
  •  臣服心动
    2020-12-28 16:39

    I ended up resolving this one via Lucene; the initial performance tests seem sufficient for our use case. A little hacking was necessary to make the prefix queries work, as I was running into the TooManyClauses exception when expanding queries such as "Jeff At*". I ended up wrapping my IndexReader with a FilterIndexReader, and set hard cap on the number of terms returned on a prefix term call. Here's my code:

    Directory directory = FSDirectory.getDirectory(indexDir);
    IndexReader reader = IndexReader.open(directory);
    FilterIndexReader filteredReader = new FilterIndexReader(reader) {
      @Override public TermEnum terms(Term t) throws IOException {
        final TermEnum origEnum = super.terms(t);
    
        return new TermEnum() {
          protected int count = 0;
          @Override public boolean next() throws IOException {
            if (count++ < (BooleanQuery.getMaxClauseCount() - 10))
              return origEnum.next();
            else return false;
          }
    
          @Override public Term term() {
            return origEnum.term();
          }
    
          @Override public int docFreq() {
            return origEnum.docFreq();
          }
    
          @Override public void close() throws IOException {
            origEnum.close();
          }
        };
      }
    };
    
    IndexSearcher searcher = new IndexSearcher(filteredReader);
    

提交回复
热议问题