因此,我们发现了Hibernate Search和Apache Solr。有人能列出它们各自的优缺点,以便我们可以选择最理想的企业搜索解决方案吗?
假设您正在使用基于注释的配置的Hibernate作为Web应用程序的持久化层。那么,您可以使用与注释一样的模型类(如下所示)来使用Solr服务器特定的注释来设置它们在Solr服务器中的索引。
我将给出一个实现此操作的示例。
以下类是一个没有Solr注释的客户端模型类。
@Entity
@Table(name="Customer")
public class Customer {
private int customerId;
private String customerName;
private String customerAddress;
@Id
public int getCustomerId() {
return customerId;
}
public void setCustomerId(int customerId) {
this.customerId = customerId;
}
public String getCustomerName() {
return customerName;
}
public void setCustomerName(String customerName) {
this.customerName = customerName;
}
public String getCustomerAddress() {
return customerAddress;
}
public void setCustomerAddress(String customerAddress) {
this.customerAddress = customerAddress;
}
}
现在,让我们使用Solr注释来索引客户在Solr服务器中的详细信息。
@Entity
@Table(name="Customer")
public class Customer {
@Field
private int customerId;
@Field
private String customerName;
@Field
private String customerAddress;
@Id
public int getCustomerId() {
return customerId;
}
public void setCustomerId(int customerId) {
this.customerId = customerId;
}
public String getCustomerName() {
return customerName;
}
public void setCustomerName(String customerName) {
this.customerName = customerName;
}
public String getCustomerAddress() {
return customerAddress;
}
public void setCustomerAddress(String customerAddress) {
this.customerAddress = customerAddress;
}
}
只需在要索引到Solr服务器的字段上添加@Field属性。
然后问题是如何告诉Solr对该模型进行索引。可以按以下方式完成。
假设您要将名为Alex的客户持久化到数据库中,则将数据添加到Alex中,如下所示:
Customer alex = new Customer();
alex.setCustomerName("Alex Rod");
alex.setCustomerAddress("101 washington st, DC");
在将这个alex对象保存到数据库后,你需要告诉Solr对这个数据对象进行索引。 操作如下。
session.save(alex);
session.getTransaction().commit();
String url = "http://localhost:8983/solr";
SolrServer server = null;
try {
server = new CommonsHttpSolrServer(url);
server.addBean(alex);
server.commit();
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
本文介绍了使用Hibernate技术进行Solr索引的相关内容,非常简单明了。我已经向您解释了如何使用它的基本思想。我们从一个商业应用程序中获得了这个例子,其中我们使用了以上方法来实现搜索功能。
除了之前提到的内容外,在群集环境下:
Hibernate-search:
缺点:
优点:
Solr/SolrCloud:
ElasticSearch
个人而言,在云中运行时我更喜欢ElasticSearch。
Apache Solr主要用于全文搜索:如果您想在一组由一个段落到几页组成的文档中查找单词(例如单数和复数)。如果您不仅仅是用它进行文本搜索,而只是进行int和varchar搜索,那么Solr可能不如常规数据库好。
这个链接可能对您有用:
http://engineering.twitter.com/2011/04/twitter-search-is-now-3x-faster_1656.html
听起来你需要阅读一下关于它们各自的优缺点的相关资料。有大量的文档可供参考。
如果你想要我的意见,我会建议你在使用 Hibernate 时使用 Hibernate Search。当 Hibernate 执行数据库操作并且仅在提交数据库事务时才会更新搜索索引。