Neo4j SDN 4 node_auto_index

Я перехожу с SDN 3 на SDN 4 и с Neo4j 2.3 на 3.0.1

У меня есть следующий запрос Search Cypher:

@Query(value = "START d=node:node_auto_index({autoIndexQuery}) MATCH (d:Decision) RETURN d")
Page<Decision> searchDecisions(@Param("autoIndexQuery") String autoIndexQuery, Pageable page);

Параметр autoIndexQuery в моем тесте соответствует следующему запросу Lucene:

(name:rdbma~0.33)^3 OR description:rdbma OR (name:mosyl~0.33)^3 OR description:mosyl

Прямо сейчас

decisionRepository.searchDecisions(autoIndexQuery, new PageRequest(page, size));

возвращает null

но отлично работает на SDN 3 и Neo4j 2.3 и возвращает Decision узлов.

Это мой Neo4jTestConfig:

@Configuration
@EnableNeo4jRepositories(basePackages = "com.example")
@EnableTransactionManagement
public class Neo4jTestConfig extends Neo4jConfiguration implements BeanFactoryAware {

    private static final String NEO4J_EMBEDDED_DATABASE_PATH_PROPERTY = "neo4j.embedded.database.path";

    @Resource
    private Environment environment;

    private BeanFactory beanFactory;

    @SuppressWarnings("deprecation")
    @Bean(destroyMethod = "shutdown")
    public GraphDatabaseService graphDatabaseService() {

        // @formatter:off
        GraphDatabaseService graphDb = new GraphDatabaseFactory()
                .newEmbeddedDatabaseBuilder(new File(environment.getProperty(NEO4J_EMBEDDED_DATABASE_PATH_PROPERTY)))       
                .setConfig(GraphDatabaseSettings.node_keys_indexable, "name,description")
                .setConfig(GraphDatabaseSettings.node_auto_indexing, "true").
                newGraphDatabase();         
        // @formatter:on

        return graphDb;
    }

    /**
     * Hook into the application lifecycle and register listeners that perform
     * behaviour across types of entities during this life cycle
     * 
     */
    @EventListener
    public void handleBeforeSaveEvent(BeforeSaveEvent event) {
        Object entity = event.getEntity();
        if (entity instanceof BaseEntity) {
            BaseEntity baseEntity = (BaseEntity) entity;
            if (baseEntity.getCreateDate() == null) {
                baseEntity.setCreateDate(new Date());
            } else {
                baseEntity.setUpdateDate(new Date());
            }
        }
    }

    @Override
    public void setBeanFactory(BeanFactory beanFactory) throws BeansException {
        this.beanFactory = beanFactory;
    }

    public BeanFactory getBeanFactory() {
        return beanFactory;
    }

    @Bean
    public org.neo4j.ogm.config.Configuration getConfiguration() {
        // @formatter:off
        org.neo4j.ogm.config.Configuration config = new org.neo4j.ogm.config.Configuration();
        config.driverConfiguration()
            .setDriverClassName("org.neo4j.ogm.drivers.embedded.driver.EmbeddedDriver");
        // @formatter:on
        return config;
    }

    @Override
    public SessionFactory getSessionFactory() {
        return new SessionFactory(getConfiguration(), "com.example");
    }

}

Что может быть не так с моей конфигурацией и как заставить ее работать на SDN 4?

ОБНОВЛЕНО

Кроме того, я нашел следующий ответ Невозможно настроить node_auto_index с InProcessServer() SDN 4, но не могу найти ServerControls и TestServerBuilders в моем пути к классам.

Это моя конфигурация индекса базы данных:

@Transactional
public class SearchDaoImpl implements SearchDao {

    @Autowired
    private DecisionRepository decisionRepository;

    @PostConstruct
    public void init() {
        EmbeddedDriver embeddedDriver = (EmbeddedDriver) Components.driver();
        GraphDatabaseService databaseService = embeddedDriver.getGraphDatabaseService();
        try (Transaction t = databaseService.beginTx()) {
            Index<Node> autoIndex = databaseService.index().forNodes("node_auto_index");
            databaseService.index().setConfiguration(autoIndex, "type", "fulltext");
            databaseService.index().setConfiguration(autoIndex, "to_lower_case", "true");
            databaseService.index().setConfiguration(autoIndex, "analyzer", StandardAnalyzerV36.class.getName());
            t.success();
        }
    }
...
}

Прямо сейчас я не знаю, где в моем коде правильное место для добавления

Components.setDriver(new EmbeddedDriver(graphDatabaseService()));

как предложено в ответах ниже

ОБНОВЛЕНО 2

@SuppressWarnings("deprecation")
@Bean(destroyMethod = "shutdown")
public GraphDatabaseService graphDatabaseService() {

    // @formatter:off
    GraphDatabaseService graphDatabaseService = new GraphDatabaseFactory()
            .newEmbeddedDatabaseBuilder(new File(environment.getProperty(NEO4J_EMBEDDED_DATABASE_PATH_PROPERTY)))       
            .setConfig(GraphDatabaseSettings.node_keys_indexable, "name,description")
            .setConfig(GraphDatabaseSettings.node_auto_indexing, "true").
            newGraphDatabase();         
    // @formatter:on        

    Components.setDriver(new EmbeddedDriver(graphDatabaseService));

    return graphDatabaseService;
}

@Override
public SessionFactory getSessionFactory() {
    return new SessionFactory("com.example");
}

Следующая конфигурация не работает с:

Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'getSession' defined in com.techbook.domain.configuration.Neo4jTestConfig: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.neo4j.ogm.session.Session]: Factory method 'getSession' threw exception; nested exception is org.neo4j.ogm.exception.ServiceNotFoundException: Driver: null
    at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:599)

person brunoid    schedule 30.05.2016    source источник


Ответы (1)


Установив свойство имени класса драйвера, EmbeddedDriver создаст частный экземпляр GraphDatabaseService, а это не то, что вам нужно, поскольку вы инициализируете его самостоятельно. Вместо этого вам нужно указать классу Components явно использовать драйвер, который вы предоставляете:

Components.setDriver(new EmbeddedDriver(graphDatabaseService()));

Это должно подключить компоненты, как вы ожидаете.

person Vince    schedule 31.05.2016
comment
Спасибо! Где эта строка кода должна быть добавлена ​​в моем приложении? - person brunoid; 31.05.2016
comment
Вероятно, проще всего сделать это в конце объявления bean-компонента GraphDatabaseService, непосредственно перед тем, как вы вернете экземпляр graphDb. - person Vince; 31.05.2016
comment
Прямо сейчас он терпит неудачу с исключением Driver: null. Я обновил свой вопрос. - person brunoid; 01.06.2016
comment
Я добавил его в @PostConstruct public void init() { Components.setDriver(new EmbeddedDriver(graphDatabaseService())); } и теперь он работает нормально - person brunoid; 01.06.2016