如何使用mongodb重建lucene索引而不是hibernate搜索jpa

时间:2014-06-03 17:39:14

标签: mongodb lucene hibernate-search

我不小心删除了我的索引目录,现在我正在尝试重建所有索引。 我正在使用带有JPA,lucene和MONGODB的hibernate搜索。

以下方法没有返回结果

    public void rebuildIndex()throws Exception{
    org.hibernate.search.jpa.FullTextEntityManager fem = org.hibernate.search.jpa.Search.getFullTextEntityManager(entityManager);

    org.hibernate.search.query.dsl.QueryBuilder queryBuilder = fem.getSearchFactory().buildQueryBuilder().forEntity(Person.class).get();

    org.apache.lucene.search.Query query = queryBuilder.all().createQuery();

    FullTextQuery fullTextQuery = fem.createFullTextQuery(query, Person.class);

    //fullTextQuery.initializeObjectsWith(ObjectLookupMethod.SKIP, DatabaseRetrievalMethod.FIND_BY_ID);

    System.out.println(fullTextQuery.toString());

    List<Person> results = fullTextQuery.getResultList();

    fem.clear(); 
    System.out.println(results.size());
    for(Person p : results){
        fem.index( p );
        fem.flushToIndexes();
        fem.clear();
    }

    //fem.createIndexer().startAndWait();  
}

该方法返回无结果。我应该如何从mongoDb获取所有数据以重建索引?

1 个答案:

答案 0 :(得分:0)

因为hibernate搜索既没有使用JPQL的标准,也没有自己的JP-QL解析器。 我无法创建一个findAll方法来检索所有objetc 唯一的方法是使用本机mongoDb查询:

org.hibernate.search.jpa.FullTextEntityManager fem = org.hibernate.search.jpa.Search.getFullTextEntityManager(entityManager);

    Mongo mongo = new Mongo("127.0.0.1", 27017);
    DB db = mongo.getDB("mainBase");
    DBCollection dbCollection = db.getCollection("Persons");
    DBCursor cursor = dbCollection.find();
    Collection<String> ids = new ArrayList<String>();
    String id = "";
    while (cursor.hasNext()) {
        id = cursor.next().get("_id").toString();
        System.out.println(id);
        ids.add(id);
    }

    System.out.println(">"+ids.size());

    Person pes;
    for(String p : ids){
        pes = new Person();
        pes.setId(p);
        pes = find(pes);
        System.out.println("indexing: "+pes.getId());
        fem.index( pes );//index each element
        fem.flushToIndexes();//apply changes to indexes
        fem.clear();//free memory since the queue is processed
    }