我正在嘗試使用Lucene 6.2爲MySQL中的數據(在Scala中使用Slick)編制索引。這裏是下面的代碼無法在Lucene 6.2中使用Scala進行搜索
package oc.api.services
/**
* Created by sujit on 9/7/16.
*/
import org.apache.lucene.document._
import org.apache.lucene.analysis.standard.StandardAnalyzer
import org.apache.lucene.index._
import org.apache.lucene.search.IndexSearcher
import java.io.{File, IOException}
import java.nio.file.Paths
import akka.actor.ActorSystem
import akka.event.{Logging, LoggingAdapter}
import akka.stream.ActorMaterializer
import oc.api.utils.{Config, DatabaseService}
import org.apache.lucene.analysis.core.KeywordAnalyzer
import org.apache.lucene.index.IndexWriterConfig.OpenMode
import org.apache.lucene.queryparser.classic.{QueryParser}
import org.apache.lucene.store.FSDirectory
import scala.concurrent.ExecutionContext
class Indexer extends Config {
implicit val actorSystem = ActorSystem()
implicit val executor: ExecutionContext = actorSystem.dispatcher
implicit val log: LoggingAdapter = Logging(actorSystem, getClass)
implicit val materializer: ActorMaterializer = ActorMaterializer()
val databaseService = new DatabaseService(jdbcUrl, dbUser, dbPassword)
val notesService = new NotesService(databaseService)
def setIndex = {
val IndexStoreDir = Paths.get("/var/www/html/LuceneIndex")
val analyzer = new KeywordAnalyzer()
val writerConfig = new IndexWriterConfig(analyzer)
writerConfig.setOpenMode(OpenMode.CREATE)
writerConfig.setRAMBufferSizeMB(500)
val directory = FSDirectory.open(IndexStoreDir)
var writer = new IndexWriter(directory, writerConfig)
val notes = notesService.getNotes() //Gets all notes from slick. Data is coming in getNotes()
var doc = new Document()
var count = 0
val stringType = new FieldType()
notes.map(_.foreach{
case(note) =>
doc = new Document()
var field = new TextField("title", note.title, Field.Store.YES)
doc.add(field)
field = new TextField("teaser", note.teaser, Field.Store.YES)
doc.add(field)
field = new TextField("description", note.description, Field.Store.YES)
doc.add(field)
writer.addDocument(doc)
})
writer.commit()
}
def search(keyword: String) = {
val IndexStoreDir = Paths.get("/var/www/html/LuceneIndex")
var directoryReader = DirectoryReader.open(FSDirectory.open(IndexStoreDir))
val analyzer = new StandardAnalyzer()
val searcher = new IndexSearcher(directoryReader)
val mqp = new QueryParser("title", analyzer) //MultiFieldQueryParser(filesToSearch,analyzer)
val query = mqp.parse(keyword)
val hits = searcher.search(query,10)
val scoreDoc = hits.scoreDocs
println(scoreDoc.length)
}
}
object Indexer extends App {
val index = new Indexer
index.setIndex
index.search("Donec")
}
setIndex函數在提供的路徑中按預期工作。但是當我根據關鍵字搜索索引時,它會拋出0結果。搜索功能有任何錯誤嗎?這怎麼解決?
第一件事,我在使用KeywordAnalyzer時犯了錯誤。其次,我在Future map中使用writer.commit。這給了我結果。謝謝你的幫助。我用正確的代碼編輯了問題。 – Sujit
如何使用Thread來實現上述代碼以優化索引過程? – Sujit
@Sujit我建議爲此打開一個新問題。 – knutwalker