我是elasticsearch的新手,尝试使用查询,日期直方图,方面从elasticsearch检索索引数据。我有弹性搜索和kibana在服务器上正常运行。现在我想从elasticsearch中提取特定的索引数据,并将其绘制为另一个本土应用程序(Spring Web应用程序)中的图形。因此,考虑使用spring数据弹性搜索,但在互联网上使用弹性搜索存储库找到了示例应用程序。
https://github.com/BioMedCentralLtd/spring-data-elasticsearch-sample-application
请帮助我使用弹簧数据弹性搜索从弹性搜索中提取数据的方法,或者是否有其他更好的方法来执行此操作。 (我不想像在示例中那样使用对象/存储库,只需要将数据作为JSON字符串获取)。
答案 0 :(得分:0)
最后我使用普通的Elasticsearch java客户端来处理。以下代码可能有用。
<bean id="esConnection" class="com.es.connection.ESConnection" scope="singleton" autowire="byName">
<property name="host" value="${es.host}" />
<property name="port" value="${es.port}" />
<property name="clusterName" value="${es.cluster}" />
</bean>
import javax.annotation.PostConstruct;
import org.elasticsearch.client.Client;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.settings.ImmutableSettings;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.transport.InetSocketTransportAddress;
public class ESConnection {
TransportClient client;
private String host;
private int port;
private String clusterName;
public ESConnection() {
}
public ESConnection(String host,int port,String clusterName) {
this.host = host;
this.clusterName = clusterName;
this.port = port;
}
@PostConstruct
public void connect() {
Settings settings = ImmutableSettings.settingsBuilder()
.put("cluster.name",clusterName)
.build();
client = new TransportClient(settings);
client.addTransportAddress(new InetSocketTransportAddress(host,port));
}
public void setHost(String host) {
this.host = host;
}
public void setPort(int port) {
this.port = port;
}
public void setClusterName(String clusterName) {
this.clusterName = clusterName;
}
public Client getClient() {
return (Client) client;
}
public void close() {
if (client != null) {
client.close();
}
}
@Override
public String toString() {
return String.format("%s, Host: %s, Port: %s, Cluster: %s", super.toString(), host, port, clusterName);
}
}
在启动监听器中,
public class StartupListener implements ServletContextListener {
@Autowired
ESConnection esConnection;
public void contextInitialized(ServletContextEvent sce) {
try {
ServletContext context = sce.getServletContext();
context.setAttribute("esConnection", esConnection);
} catch (SchedulerException se) {
} catch (Exception e) {
}
}
public void contextDestroyed(ServletContextEvent sce) {
ServletContext context = sce.getServletContext();
if (this.esConnection != null) {
this.esConnection.close();
context.removeAttribute("esConnection");
}
}
}