您的位置:首页 > 数据库

数据库数据构建文件索引

2018-03-07 11:19 155 查看
//生成索引
public void buildIndex(final List<Knowledge> k) throws Exception
{

Thread t = new Thread(new Runnable()
{
public void run()
{

IndexWriter iwriter = null;
try
{
// run方法具体重写
analyzer = new StandardAnalyzer();
// 将索引存储到内存中
// Directory directory = new RAMDirectory();
// 将索引存储到硬盘上
directory = FSDirectory.open(Paths.get(Constant.ADRESS));
IndexWriterConfig config = new IndexWriterConfig(analyzer);
iwriter = new IndexWriter(directory, config);

for (Knowledge l : k)
{
Document doc = new Document();
doc.add(new Field(Constant.ID, l.getKnowId().toString(), TextField.TYPE_STORED));
doc.add(new Field(Constant.TITLE, l.getKnowTitle(), TextField.TYPE_STORED));
doc.add(new Field(Constant.KNOWCONTENT, l.getKnowContent().replaceAll("<br>", ","), TextField.TYPE_STORED));

iwriter.addDocument(doc);
updateStatetwo(l);//更改数据库索引标识为已生成
}

iwriter.close();
directory.close();

}
catch (Exception e)
{

e.printStackTrace();
try
{
iwriter.close();
}
catch (Exception e1)
{
e1.printStackTrace();

}

}

}
});
t.run();
;

}

public List<Knowledge> getKnowledgeByid(final String value)
{
final List<Knowledge> knowledges = new ArrayList<Knowledge>();

Thread t = new Thread(new Runnable()
{

@Override
public void run()
{

// run方法具体重写
analyzer = new StandardAnalyzer();
// 将索引存储到内存中
// Directory directory = new RAMDirectory();
// 将索引存储到硬盘上
try
{
directory = FSDirectory.open(Paths.get(Constant.ADRESS));

// 读取索引并查询
DirectoryReader ireader = DirectoryReader.open(directory);
IndexSearcher isearcher = new IndexSearcher(ireader);
// 解析一个简单的查询
QueryParser parser = new QueryParser(Constant.KNOWCONTENT, analyzer);
Query query = parser.parse(value);

ScoreDoc[] hits = isearcher.search(query, 1000).scoreDocs;
// 迭代输出结果
String buff = null;
for (int i = 0; i < hits.length; i++)
{
Document hitDoc = isearcher.doc(hits[i].doc);
Knowledge k = new Knowledge();
k.setKnowId(Integer.parseInt(hitDoc.get(Constant.ID)));
k.setKnowTitle(hitDoc.get(Constant.TITLE));
k.setKnowContent(hitDoc.get(Constant.KNOWCONTENT));
buff = hitDoc.get(Constant.KNOWCONTENT);
if (buff.length() > 80)
{
k.setLitile(buff.substring(0, 80));
}
else
{
k.setLitile(hitDoc.get(Constant.KNOWCONTENT));
}
knowledges.add(k);//加入集合抛出
}
ireader.close();
directory.close();

}
catch (IOException e)
{
e.printStackTrace();
}
catch (ParseException e)
{
e.printStackTrace();
}

}
});

t.run();

return knowledges;

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐