繁体   English   中英

在lucene中添加对象列表

[英]add list of objects in lucene

我使用lucene 4.7.0存储数据。 我想在Lucene文档中添加对象列表。 例如

Class A{
    private List<B> listOfB;
    private String  field1;
}

Class B {
    private String name;
    private String  date;
}

我想添加很简单的field1,但是如何在A的Lucene文档中存储“ listofB”?

谢谢桑比

这样做的方法有很多,有时取决于您的业务。

我们遇到了相同的情况,在这种情况下我们所做的如下:

第一

我们确定应添加到索引的字段及其类型。 在此确定字段值的类型,将其设置为单个值还是列表等。

第二

如果字段是像您的案例那样的对象列表,我们只需遍历该列表,然后将该对象中的每个字段添加为单独的(有时),或者将该对象字段值组合为一个String值,然后将其添加为a。

例如

for (B b : list) {
    luceneDoc.add(new TextField(KEY, b.getName(), STORE_TYPE));
    luceneDoc.add(new TextField(KEY, b.getDate(), STORE_TYPE));
}

要么

for (B b : list) {
    luceneDoc.add(new TextField(KEY, getBfieldsValue(b), STORE_TYPE));//getBfieldsValue(b) should return a one String value from all B fields.
}

注意: 我以TextField为例,您应该根据业务使用字段类型。

这是一个古老的问题,我没有看到任何回应- 我们能否将类重构为对象? 所以在这里回答。

基本上,您必须使用序列化和反序列化来存储和检索复杂对象作为Lucene Document字段。

我关注了这篇文章

我正在使用Lucene 6.6。 以下是示例代码,作为“索引和搜索”的一部分,

Document doc = new Document();
        doc.add(new TextField("content", startBean.getIndexable(), Field.Store.NO));

        ByteArrayOutputStream serData=new ByteArrayOutputStream(); 
        ObjectOutputStream out=new ObjectOutputStream(serData);

        try { 
            out.writeObject(startBean); 
        } finally  { 
            out.close(); 
            serData.close(); 
        } 

        FieldType filedType = new FieldType();
        filedType.setStored(true);
        filedType.setTokenized(false);

        doc.add(new Field("storedcontent",serData.toByteArray(),filedType));

        writer.addDocument(doc);

基本上,我有类型的POJO - StartBean与实例作为startBean 它有一个String字段,我将startBean用作Lucene索引字段,并将完整的startBean作为byte[]存储在Lucene索引中。

然后在搜索时,如果找到了匹配项,

我愿意- Document doc = searcher.doc(hit.doc); 然后调用以下方法StartBean startBean = getStartBean(doc); 重建我的对象。

private StartBean getStartBean(Document document) throws ClassNotFoundException, IOException{

        StartBean startBean = null;

        BytesRef binaryValue = document.getBinaryValue("storedcontent");

        if(null != binaryValue){
            System.out.println("binaryValue is non null ");

            byte[] bytes = binaryValue.bytes;

            ObjectInputStream in=new ObjectInputStream(new 
                    ByteArrayInputStream(bytes)); 
                            try { 
                                startBean = (StartBean) in.readObject(); 
                            } finally  { 
                                    in.close(); 
                            } 
        }

        return startBean;

    }

您必须确保父对象和嵌套对象是可Serializable或标记为transient (基本序列化-反序列化规则)。

让我知道任何代码部分的澄清。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM