3

我有一个需要被 Hibernate Search 索引的域对象。当我在我的 DEV 机器上对这个对象执行 FullTextQuery 时,我得到了预期的结果。然后我将应用程序部署到 WAR 并将其分解到我的 PROD 服务器(VPS)。当我在我的 PROD 机器上执行相同的“搜索”时,我根本没有得到预期的结果(似乎缺少一些结果)。

我已经运行 LUKE 以确保所有内容都已正确编入索引,并且似乎所有内容都在应有的位置...我是 Hibernate Search 的新手,因此将不胜感激。

这是我的域对象:

package com.chatter.domain;

import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;

import org.apache.solr.analysis.LowerCaseFilterFactory;
import org.apache.solr.analysis.SnowballPorterFilterFactory;
import org.apache.solr.analysis.StandardTokenizerFactory;
import org.hibernate.search.annotations.AnalyzerDef;
import org.hibernate.search.annotations.Field;
import org.hibernate.search.annotations.Index;
import org.hibernate.search.annotations.Indexed;
import org.hibernate.search.annotations.IndexedEmbedded;
import org.hibernate.search.annotations.Parameter;
import org.hibernate.search.annotations.Store;
import org.hibernate.search.annotations.TokenFilterDef;
import org.hibernate.search.annotations.TokenizerDef;

@Entity
@Table(name="faq")
@Indexed()
@AnalyzerDef(name = "customanalyzer",
tokenizer = @TokenizerDef(factory = StandardTokenizerFactory.class),
filters = {
  @TokenFilterDef(factory = LowerCaseFilterFactory.class),
  @TokenFilterDef(factory = SnowballPorterFilterFactory.class, params = {
    @Parameter(name = "language", value = "English")
  })
})
public class CustomerFaq implements Comparable<CustomerFaq>
{
  private Long id;
  @IndexedEmbedded
  private Customer customer;
  @Field(index=Index.TOKENIZED, store=Store.NO)
  private String question;
  @Field(index=Index.TOKENIZED, store=Store.NO)
  private String answer;

  @Id
  @GeneratedValue(strategy = GenerationType.AUTO)
  public Long getId()
  {
    return id;
  }
  public void setId(Long id)
  {
    this.id = id;
  }

  @ManyToOne(fetch=FetchType.EAGER, cascade=CascadeType.ALL)
  @JoinColumn(name="customer_id")
  public Customer getCustomer()
  {
    return customer;
  }
  public void setCustomer(Customer customer)
  {
    this.customer = customer;
  }

  @Column(name="question", length=1500)
  public String getQuestion()
  {
    return question;
  }
  public void setQuestion(String question)
  {
    this.question = question;
  }

  @Column(name="answer", length=1500)
  public String getAnswer()
  {
    return answer;
  }
  public void setAnswer(String answer)
  {
    this.answer = answer;
  }
  @Override
  public int hashCode()
  {
    final int prime = 31;
    int result = 1;
    result = prime * result + ((id == null) ? 0 : id.hashCode());
    return result;
  }
  @Override
  public boolean equals(Object obj)
  {
    if (this == obj) return true;
    if (obj == null) return false;
    if (getClass() != obj.getClass()) return false;
    CustomerFaq other = (CustomerFaq) obj;
    if (id == null)
    {
      if (other.id != null) return false;
    } else if (!id.equals(other.id)) return false;
    return true;
  }
  @Override
  public int compareTo(CustomerFaq o)
  {
    if (this.getCustomer().equals(o.getCustomer()))
    {
      return this.getId().compareTo(o.getId());
    }
    else
    {
      return this.getCustomer().getId().compareTo(o.getCustomer().getId());
    }
  }
}

这是我的客户域对象的片段:

import org.hibernate.search.annotations.Field;
import org.hibernate.search.annotations.Index;
import org.hibernate.search.annotations.Store;
import javax.persistence.Entity;
// ... other imports

@Entity
public class Customer
{
  @Field(index=Index.TOKENIZED, store=Store.YES)
  private Long id;

  // ... other instance vars

  @Id
  @GeneratedValue(strategy = GenerationType.AUTO)
  public Long getId()
  {
    return id;
  }
  public void setId(Long id)
  {
    this.id = id;
  }

还有我的persistence.xml:

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<persistence xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="2.0" xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd">
<persistence-unit name="persistenceUnit" transaction-type="RESOURCE_LOCAL">
        <provider>org.hibernate.ejb.HibernatePersistence</provider>
        <properties>
            <property name="hibernate.dialect" value="org.hibernate.dialect.MySQL5InnoDBDialect"/>
            <!-- value="create" to build a new database on each run; value="update" to modify an existing database; value="create-drop" means the same as "create" but also drops tables when Hibernate closes; value="validate" makes no changes to the database -->
            <property name="hibernate.hbm2ddl.auto" value="update"/>
            <property name="hibernate.ejb.naming_strategy" value="org.hibernate.cfg.ImprovedNamingStrategy"/>
            <property name="hibernate.connection.charSet" value="UTF-8"/>
            <!-- Hibernate Search configuration -->
            <property name="hibernate.search.default.directory_provider"
                value="filesystem" />
            <property name="hibernate.search.default.indexBase" value="C:/lucene/indexes" />


        </properties>
    </persistence-unit>
</persistence>

最后,这是 DAO 中使用的查询:

public List<CustomerFaq> searchFaqs(String question, Customer customer)
  {
    FullTextSession fullTextSession = Search.getFullTextSession(sessionFactory.getCurrentSession());
    QueryBuilder queryBuilder = fullTextSession.getSearchFactory().buildQueryBuilder().forEntity(CustomerFaq.class).get();
    org.apache.lucene.search.Query luceneQuery = queryBuilder.keyword().onFields("question", "answer").matching(question).createQuery();

    org.hibernate.Query fullTextQuery = fullTextSession.createFullTextQuery(luceneQuery, CustomerFaq.class);

    List<CustomerFaq> matchingQuestionsList = fullTextQuery.list();
    log.debug("Found " + matchingQuestionsList.size() + " matching questions");
    List<CustomerFaq> list = new ArrayList<CustomerFaq>();
    for (CustomerFaq customerFaq : matchingQuestionsList)
    {
      log.debug("Comparing " + customerFaq.getCustomer() + " to " + customer + " -> " + customerFaq.getCustomer().equals(customer));
      log.debug("Does list already contain this customer FAQ? " + list.contains(customerFaq));
      if (customerFaq.getCustomer().equals(customer) && !list.contains(customerFaq))
      {
        list.add(customerFaq);
      }
    }
    log.debug("Returning " + list.size() + " matching questions based on customer: " + customer);
    return list;
  }
4

3 回答 3

1

看起来我的软件查找 indexBase 的实际位置不正确。

当我查看日志时,我注意到它在加载 indexBase 时引用了两个不同的位置。

Hibernate Search 加载此 indexBase 的一个位置来自“C:/Program Files/Apache Software Foundation/Tomcat 6.0/tmp/indexes”,然后稍后在日志中(在启动阶段)我看到它也是从我在 persistence.xml 文件(“C:/lucene/indexes”)中设置的位置加载。

所以意识到这一点,我只是更改了我的 persistence.xml 文件中的位置以匹配它(出于某种原因)也在寻找的位置。一旦这两个匹配,宾果,一切正常!

于 2013-08-20T16:12:12.167 回答
0

我可以在您的 persistence.xml 配置中看到您在 Mysql 下。谷歌搜索一些关于不同环境中相同查询的 sql 概念,我发现存在来自相同查询的缓存 mysql 结果集,但是这个缓存可能会根据环境中的新变量(如字符集)而改变。您也可以从您的 Mysql 服务器禁用此功能。

引自 Hibernate In Action - Bauer, C. King, G. 第 55 页(第 2.4.3 节日志记录)

但是,尤其是在面对异步行为时,调试 Hibernate 会很快让你迷失方向。您可以使用日志记录来查看 Hibernate 的内部结构。我们已经提到过 *hibernate.show_sql* 配置参数,它通常是故障排除时的第一个调用端口。有时单靠 SQL 是不够的;在这种情况下,您必须深入挖掘。Hibernate 使用 Apache commons-logging记录所有有趣的事件,这是一个薄抽象层,将输出定向到 Apache log4j(如果您将log4j.jar 放在类路径中)或JDK1.4日志记录(如果您在 JDK1.4 或更高版本下运行)并且 log4j 不存在)。我们推荐log4j,因为它更成熟,更流行,并且正在更积极的开发中。要查看log4j的任何输出,您需要在类路径中(在hibernate.propertieshibernate.cfg.xml旁边)中有一个名为log4j.properties的文件。此示例将所有日志消息定向到控制台:

### 将日志消息直接记录到标准输出###

log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target=System.out
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}:%L - %m%n

### 根记录器选项###

log4j.rootLogger=warn, stdout

### 休眠日志记录选项###

log4j.logger.net.sf.hibernate=info

### 记录 JDBC 绑定参数 ###

log4j.logger.net.sf.hibernate.type=info

### 记录 PreparedStatement 缓存活动 ###

log4j.logger.net.sf.hibernate.ps.PreparedStatementCache=info

使用此配置,您将不会在运行时看到很多日志消息。将log4j.logger.net.sf.hibernate类别的 info 替换为 debug将揭示 Hibernate 的内部工作原理。确保您不在生产环境中执行此操作——写入日志将比实际访问数据库慢得多。最后,您拥有 hibernate.properties、hibernate.cfg.xml 和 log4j.properties 配置文件。

于 2013-07-28T09:25:04.463 回答
0

只是盲目地拍摄,如果可能的话,让你的 DEV 环境指向 PROD DB,看看你是否得到了你期望的结果。只是为了放弃并 100% 确定你在真正的问题面前:)

于 2013-07-26T10:33:55.430 回答