我正在尝试使用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