关于如何使用ElasticJavaClient与AWSElasticsearchService对话?和elasticsearch客户端java的问题就给大家分享到这里,感谢你花时间阅读本站内容,更多关
关于如何使用Elastic Java Client与AWS Elasticsearch Service对话?和elasticsearch客户端 java的问题就给大家分享到这里,感谢你花时间阅读本站内容,更多关于amazon-web-services – Elastic Beanstalk上的ElasticSearch、com.amazonaws.services.elasticbeanstalk.AWSElasticBeanstalkClient的实例源码、Elasticsearch - 如何在java中使用elasticsearch查找与地理定位点的匹配项、ElasticSearch - 学习笔记 02-springboot 整合 jestclient 操作 elasticSearch等相关知识的信息别忘了在本站进行查找喔。
本文目录一览:- 如何使用Elastic Java Client与AWS Elasticsearch Service对话?(elasticsearch客户端 java)
- amazon-web-services – Elastic Beanstalk上的ElasticSearch
- com.amazonaws.services.elasticbeanstalk.AWSElasticBeanstalkClient的实例源码
- Elasticsearch - 如何在java中使用elasticsearch查找与地理定位点的匹配项
- ElasticSearch - 学习笔记 02-springboot 整合 jestclient 操作 elasticSearch
如何使用Elastic Java Client与AWS Elasticsearch Service对话?(elasticsearch客户端 java)
我已经使用AWS Elasticsearch Service(Not EC2)设置了Elasticsearch服务器。它给了我一个端点https://xxx-xxxxxxxx.us-
west-2.es.amazonaws.com/,如果我单击该端点(请注意,没有指定端口),我可以得到预期的结果
{ status: 200, name: "Mastermind", cluster_name: "xxxx", version: { number: "1.5.2", build_hash: "yyyyyy", build_timestamp: "2015-04-27T09:21:06Z", build_snapshot: false, lucene_version: "4.10.4" }, tagline: "You Know, for Search"}
问题是如何在没有端口号的情况下通过Elasticsearch Java客户端获取此信息?我得到的示例代码是
Client client = TransportClient.builder().build() .addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("host1"), 9300));
如果我使用此代码,并用端点替换“ host1”,则将得到“ NoNodeAvailableException”
ps:我使用的Java客户端版本是2.0.0。
编辑 我最终决定与第三方REST客户端Jest一起使用。但是Brooks在下面回答的内容也非常有用-AWS确实将端口80用于http,将443用于https。对我来说,阻止者是防火墙。
Edit2 AWS ES服务文档明确表示:
该服务在端口80上支持HTTP,但不支持TCP传输。
答案1
小编典典信不信由你,AWS不会使用9200和9300启动Elasticsearch。它是通过普通的旧端口80启动的。
因此,为了演示,请尝试…
curl -XPOST "http://xxx-xxxxxxxx.us-west-2.es.amazonaws.com:80/myIndex/myType" -d ''["name":"Edmond"}''
要么
curl -XPOST "https://xxx-xxxxxxxx.us-west-2.es.amazonaws.com:443/myIndex/myType" -d ''["name":"Edmond"}''
它的响应应为:{“ index”:“ myIndex”,“ _ type”:“ myType”,“ _ id”:“ SOME_ID #”,“ _version”:1,“ created”:true}
签入Kibana,您会发现它在那里。
因此,在您的代码中,它应该是:
Client client = TransportClient.builder().build() .addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("xxx-xxxxxxxx.us-west-2.es.amazonaws.com"), 80));
不幸的是,我不了解如何使用传输客户端通过SSL / HTTPS传输加密。您可以尝试使用常规的REST调用来代替使用JERSEY。
最后,确保正确配置了Elasticsearch访问策略。类似于以下内容:
{ "Version": "2012-10-17", "Statement": [ { "Sid": "", "Effect": "Allow", "Principal": "*", "Action": "es:*", "Resource": "arn:aws:es:us-east-1:yyyyyyy:domain/myDomain/*" }, { "Sid": "", "Effect": "Allow", "Principal": "*", "Action": "es:*", "Resource": "arn:aws:es:us-east-1:yyyyyyyyy:domain/myDomain" } ]}
注意: 上面的访问策略是完全开放的,不建议在远程生产环境中使用。请注意…
amazon-web-services – Elastic Beanstalk上的ElasticSearch
我正在尝试让ElasticSearch在Elastic Beanstalk环境中运行.使用Docker镜像,在负载平衡环境中运行一个实例非常简单.但是,当我尝试向群集添加更多实例时,它们无法发现彼此,并且每个新实例都成为new_master.
我的Dockerfile看起来如下
FROM dockerfile/java:oracle-java8
RUN ... # Downloading and installing ElasticSearch
RUN /elasticsearch/bin/plugin install elasticsearch/elasticsearch-cloud-aws/2.5.0
VOLUME ["/data"]
ADD config/elasticsearch.yml /elasticsearch/config/elasticsearch.yml
workdir /data
CMD ["/elasticsearch/bin/elasticsearch"]
EXPOSE 9200
配置config / elasticsearch.yml如下所示:
cluster:
name: elastic-env-dev
cloud:
aws:
region: ap-southeast-2
discovery:
type: ec2
ec2:
tag:
Name: elastic-env-dev
ping_timeout: 120s
EB环境的名称是elastic-env-dev.
http://vladmiller.com/elasticsearch/aws/2015/12/08/deploy-elasticsearch-on-aws-elasticbeanstalk.html
此时(2015年11月14日),经过一段时间后,我会说不可能让ES集群在EB上运行.
问题#1是您必须将docker端口映射到主机,就像您一样
docker run -p 9300:9300 ...
如果您通过.ebextensions添加post appdeploy hook,这将设置iptables端口转发,这可以很容易地解决
files:
"/opt/elasticbeanstalk/hooks/appdeploy/post/99_setup_iptables.sh":
mode: "0755"
owner: root
group: root
content: |
#!/bin/sh
iptables-save | grep -v added_by_ebextension | iptables-restore
DOCKER_IP=$(docker inspect `cat /etc/elasticbeanstalk/.aws_beanstalk.current-container-id` | jq -r .[0].NetworkSettings.IPAddress)
iptables -t nat -A DOCKER -p tcp --dport 9300:9400 -j DNAT --to-destination ${DOCKER_IP} -m comment --comment added_by_ebextension
service iptables save
问题#2您需要调整安全组,确保在SG中的节点之间允许TCP 9300-9400和ICMP流量.
问题#3使用aws-ec2发现插件并将其限制在你的SG,因此没有其他机器被发现
// elasticsearch.yml
cloud.aws:
access_key: YYYYYYYYY
secret_key: XXXXXXXXX
region: us-east-1
discovery.type: ec2
discovery.ec2.ping_timeout: 30s
discovery.ec2.tag.Name: [ENVIRONMENT_NAME]
discovery.ec2.host_type: private_dns
discovery.zen.ping.multicast.enabled: false
问题#4,未解决的是每个ES节点将绑定到内部docker IP地址,类似于172.17.0.3,但是您的主机私有IP是不同的.因此,当节点发现彼此并开始通信时,他们将向其他人报告错误的IP地址.
[2015-11-13 21:50:58,542][TRACE][discovery.zen.ping.unicast] [86ac0ad55d5b] [2] received response from {#zen_unicast_21_#cloud-i-8c317a3b-0#}{10.165.71.177}{ip-10-165-71-177.ec2.internal/10.165.71.177:9300}: [ping_response{node [{86ac0ad55d5b}{U3PF5qOaQCucpK3JfZ3ara}{172.17.0.3}{172.17.0.3:9300}],id[5],master [null],hasJoinedOnce [false],cluster_name[es-staging]},ping_response{node [{86ac0ad55d5b}{U3PF5qOaQCucpK3JfZ3ara}{172.17.0.3}{172.17.0.3:9300}],id[7],id[9],id[11],ping_response{node [{89764d1bb185}{yVRC-HmIQoayIuWfi6a09g}{172.17.0.3}{172.17.0.3:9300}],id[30],master [{89764d1bb185}{yVRC-HmIQoayIuWfi6a09g}{172.17.0.3}{172.17.0.3:9300}],hasJoinedOnce [true],cluster_name[es-staging]}]
您可以在ip-10-165-71-177.ec2.internal / 10.165.71.177:9300上看到该节点被发现,但是该节点响应它的IP是172.17.0.3,因此第一个节点而不是连接到EC2私有IP将尝试连接到内部Docker IP
[2015-11-13 21:51:00,037][TRACE][discovery.ec2 ] [86ac0ad55d5b] full ping responses:
--> ping_response{node [{89764d1bb185}{yVRC-HmIQoayIuWfi6a09g}{172.17.0.3}{172.17.0.3:9300}],cluster_name[es-staging]}
[2015-11-13 21:51:00,041][DEBUG][discovery.ec2 ] [86ac0ad55d5b] filtered ping responses: (filter_client[true],filter_data[false])
--> ping_response{node [{89764d1bb185}{yVRC-HmIQoayIuWfi6a09g}{172.17.0.3}{172.17.0.3:9300}],cluster_name[es-staging]}
我们需要以某种方式使ES绑定到主机的IP地址或忽略这些docker IP地址并继续发现的IP.
更新1我怀疑你可以在没有Docker的情况下将ES部署到EB,但是我还没有尝试过这个选项.
更新2我能够让节点发现彼此并尝试通信,但现在它有一个different issue
更新3这是关于如何达到预期效果http://vladmiller.com/elasticsearch/aws/2015/12/08/deploy-elasticsearch-on-aws-elasticbeanstalk.html的故事和示例代码
com.amazonaws.services.elasticbeanstalk.AWSElasticBeanstalkClient的实例源码
public void execute() { checkParams(); AWSElasticBeanstalkClient bcclient = getorCreateClient(AWSElasticBeanstalkClient.class); DescribeEnvironmentsRequest deRequest = new DescribeEnvironmentsRequest() .withEnvironmentNames(environmentName); DescribeEnvironmentsResult result = bcclient .describeEnvironments(deRequest); if (result.getEnvironments().size() < 1) { throw new BuildException( "No environments found with the specified name " + environmentName); } try { AWSTestUtils.waitForEnvironmentToTransitionToStateAndHealth( environmentName,EnvironmentStatus.Ready,null,bcclient); } catch (InterruptedException e) { throw new BuildException(e.getMessage()); } }
@Override public boolean perform() throws Exception { AWSClientFactory factory; if (null != getDeployerConfig().getCredentials()) { factory = AWSClientFactory .getClientFactory(getDeployerConfig().getCredentials(),getDeployerConfig().getAwsRegion()); } else { factory = AWSClientFactory.getClientFactory("",getDeployerConfig().getAwsRegion()); } log ("Using region: '%s'",getDeployerConfig().getAwsRegion()); setS3(factory.getService(AmazonS3Client.class)); setAwseb(factory.getService(AWSElasticBeanstalkClient.class)); return false; }
/** * Environment can collect events from running environment. * @throws Exception If something is wrong */ @Test public void collectsEventsFromLiveEnvironment() throws Exception { Assume.assumeThat(EnvironmentTest.AWS_KEY,Matchers.notNullValue()); final AWSCredentials creds = new BasicAWSCredentials( EnvironmentTest.AWS_KEY,EnvironmentTest.AWS_SECRET ); final AWSElasticBeanstalk ebt = new AWSElasticBeanstalkClient(creds); final Environment env = new Environment(ebt,"e-nxmcbf3pvk"); Logger.info( this,"events: %[list]s",Arrays.asList(env.events()) ); }
/** * Create a new Beanstalk application version using the file on S3 at s3BucketName/s3FileKey. * Deploy this application version to the Beanstalk environment. */ public void deployToEnvironment() { this.info("Connecting to ElasticBeanstalk"); AWSElasticBeanstalkClient beanstalkClient = new AWSElasticBeanstalkClient(this.mvnArgs.getCredentials()); // create new application version this.info("Creating new version " + this.mvnArgs.applicationName + "/" + this.mvnArgs.applicationVersion); S3Location s3Location = new S3Location() .withS3Bucket(this.mvnArgs.s3BucketName) .withS3Key(this.mvnArgs.s3FileKey); CreateApplicationVersionRequest versionRequest = new CreateApplicationVersionRequest() .withApplicationName(this.mvnArgs.applicationName) .withVersionLabel(this.mvnArgs.applicationVersion) .withSourceBundle(s3Location); CreateApplicationVersionResult versionResult = beanstalkClient.createApplicationVersion(versionRequest); Util.dump(versionResult,this.mvnArgs.getLog()); // tell the environment to use the new application version this.info("Updating environment " + this.mvnArgs.environmentName + " with version " + this.mvnArgs.applicationVersion); UpdateEnvironmentRequest environmentRequest = new UpdateEnvironmentRequest() .withEnvironmentName(this.mvnArgs.environmentName) .withVersionLabel(this.mvnArgs.applicationVersion); UpdateEnvironmentResult envResult = beanstalkClient.updateEnvironment(environmentRequest); Util.dump(envResult,this.mvnArgs.getLog()); }
public void execute() { checkParams(); AWSElasticBeanstalkClient client = getorCreateClient(AWSElasticBeanstalkClient.class); CreateApplicationRequest request = new CreateApplicationRequest( applicationName).withDescription(applicationDescription); System.out.println("Creating application " + applicationName + "..."); try { client.createApplication(request); } catch (Exception e) { throw new BuildException( "Exception while attempting to create application: " + e.getMessage(),e); } System.out.println("Application created successfully"); }
public void execute() { System.out .println("Terminating environment " + environmentName + "..."); checkParams(); AWSElasticBeanstalkClient bcclient = getorCreateClient(AWSElasticBeanstalkClient.class); try { bcclient.terminateEnvironment(new TerminateEnvironmentRequest() .withEnvironmentName(environmentName)); } catch (Exception e) { throw new BuildException("Could not terminate environment " + e.getMessage(),e); } System.out .println("The request to terminate the environment has been submitted."); }
public static void waitForEnvironmentToTransitionToStateAndHealth( String environmentName,EnvironmentStatus state,EnvironmentHealth health,AWSElasticBeanstalkClient bcclient) throws InterruptedException { System.out.println("Waiting for instance " + environmentName + " to transition to " + state + "/" + health); int count = 0; while (true) { Thread.sleep(1000 * 30); if (count++ > 100) { throw new RuntimeException("Environment " + environmentName + " never transitioned to " + state + "/" + health); } List<EnvironmentDescription> environments = bcclient .describeEnvironments( new DescribeEnvironmentsRequest() .withEnvironmentNames(environmentName)) .getEnvironments(); if (environments.size() == 0) { System.out .println("No environments with that name were found."); return; } EnvironmentDescription environment = environments.get(0); System.out.println(" - " + environment.getStatus() + "/" + environment.getHealth()); if (environment.getStatus().equalsIgnoreCase(state.toString()) == false) continue; if (health != null && environment.getHealth().equalsIgnoreCase( health.toString()) == false) continue; return; } }
/** * Environment can deploy and reverse with a broken WAR file. This test * has to be executed only if you have full access to AWS S3 bucket,and * AWS EBT for deployment. The test runs full cycle of deployment and then * destroying of a new environment. It won't hurt anything,but will * consume some EBT resources. Be careful. * * @throws Exception If something is wrong */ @Test public void deploysAndReversesWithLiveAccount() throws Exception { Assume.assumeThat(ApplicationTest.AWS_KEY,Matchers.notNullValue()); final AWSCredentials creds = new BasicAWSCredentials( ApplicationTest.AWS_KEY,ApplicationTest.AWS_SECRET ); final AWSElasticBeanstalk ebt = new AWSElasticBeanstalkClient(creds); final String name = "netbout"; final Application app = new Application(ebt,name); final File war = this.temp.newFile("temp.war"); FileUtils.writeStringToFile(war,"broken JAR file content"); final Environment candidate = app.candidate( new OverridingVersion( ebt,name,new OverridingBundle( new AmazonS3Client(creds),"webapps.netbout.com",war.getName(),war ) ),name ); MatcherAssert.assertthat(candidate.green(),Matchers.equalTo(false)); Logger.info(this,"tail report:\n%s",candidate.tail()); candidate.terminate(); }
/** * Environment can fetch TAIL report from live environment. * @throws Exception If something is wrong */ @Test public void fetchesTailReportFromLiveEnvironment() throws Exception { Assume.assumeThat(EnvironmentTest.AWS_KEY,"e-2n2mqauqae"); Logger.info(this,env.tail()); }
public BeanstalkDeployer(String s3Endpoint,String beanstalkEndpoint,AWSCredentialsProvider credentialsProvider) { s3 = new AmazonS3Client(credentialsProvider); elasticBeanstalk = new AWSElasticBeanstalkClient(credentialsProvider); s3.setEndpoint(s3Endpoint); elasticBeanstalk.setEndpoint(beanstalkEndpoint); }
public static AWSElasticBeanstalk getElasticBeanstalk(AWSCredentialsProvider credentials,Region region) { AWSElasticBeanstalk awseb = region.createClient(AWSElasticBeanstalkClient.class,credentials,getClientConfig()); return awseb; }
public void execute() { checkParams(); AWSElasticBeanstalkClient client = getorCreateClient(AWSElasticBeanstalkClient.class); CreateEnvironmentRequest eRequest = new CreateEnvironmentRequest( applicationName,environmentName) .withDescription(environmentDescription) .withVersionLabel(versionLabel) .withSolutionStackName(solutionStackName); if (!(tierName == null || tierType == null || tierVersion == null)) { eRequest.setTier(new EnvironmentTier().withName(tierName) .withType(tierType).withVersion(tierVersion)); } if (cnamePrefix != null) { CheckDNSAvailabilityResult dnsResult = client .checkDNSAvailability(new CheckDNSAvailabilityRequest( cnamePrefix)); if (!dnsResult.isAvailable()) { throw new BuildException("The specified CNAME " + cnamePrefix + " was not available"); } eRequest.setCNAMEPrefix(cnamePrefix); } List<ConfigurationoptionSetting> optionSettings = new LinkedList<ConfigurationoptionSetting>(); for (Setting setting : settings) { optionSettings.add(new ConfigurationoptionSetting(setting .getNamespace(),setting.getoptionName(),setting .getValue())); } if (optionSettings.size() > 0) { eRequest.setoptionSettings(optionSettings); } System.out.println("Creating environment " + environmentName + "..."); String cNAME = ""; try { CreateEnvironmentResult result = client.createEnvironment(eRequest); if ((cNAME = result.getCNAME()) == null) { System.out .println("Create environment request submitted. The environment configuration does not support a CNAME."); } else { System.out .println("Create environment request submitted. When the environment is finished launching,your deployment will be available at " + cNAME); } } catch (Exception e) { throw new BuildException( "Exception while attempting to create environment: " + e.getMessage(),e); } }
public void execute() { checkParams(); AWSElasticBeanstalkClient bcclient = getorCreateClient(AWSElasticBeanstalkClient.class); bcclient.deleteApplication(new DeleteApplicationRequest(applicationName)); }
public FormValidation dovalidateCredentials( @QueryParameter("credentialId") final String credentialId,@QueryParameter final String awsRegion) { for (String value : Arrays.asList(credentialId,awsRegion)) { if (value.contains("$")) { return FormValidation.warning("Validation skipped due to parameter usage ('$')"); } } StringWriter stringWriter = new StringWriter(); PrintWriter w = new PrintWriter(stringWriter,true); try { w.printf("<ul>%n"); w.printf("<li>Building Client (credentialId: '%s',region: '%s')</li>%n",credentialId,awsRegion); AWSClientFactory factory = AWSClientFactory.getClientFactory(credentialId,awsRegion); AmazonS3 amazonS3 = factory.getService(AmazonS3Client.class); String s3Endpoint = factory.getEndpointFor((AmazonS3Client) amazonS3); w.printf("<li>Testing Amazon S3 Service (endpoint: %s)</li>%n",s3Endpoint); w.printf("<li>Buckets Found: %d</li>%n",amazonS3.listBuckets().size()); AWSElasticBeanstalk awsElasticBeanstalk = factory.getService(AWSElasticBeanstalkClient.class); String awsEBEndpoint = factory.getEndpointFor((AWSElasticBeanstalkClient) awsElasticBeanstalk); w.printf("<li>Testing AWS Elastic Beanstalk Service (endpoint: %s)</li>%n",awsEBEndpoint); List<String> applicationList = Lists.transform(awsElasticBeanstalk.describeApplications().getApplications(),new Function<ApplicationDescription,String>() { @Override public String apply(ApplicationDescription input) { return input.getApplicationName(); } }); w.printf("<li>Applications Found: %d (%s)</li>%n",applicationList.size(),StringUtils.join(applicationList,",")); w.printf("</ul>%n"); return FormValidation.okWithMarkup(stringWriter.toString()); } catch (Exception exc) { return FormValidation.error(exc,"Failure"); } }
Elasticsearch - 如何在java中使用elasticsearch查找与地理定位点的匹配项
如何解决Elasticsearch - 如何在java中使用elasticsearch查找与地理定位点的匹配项?
我是 elasticSearch 的新手,我正在尝试查询与地图上特定点匹配的文档,我正在使用 GeoPoint 对象,我需要进行一个返回所有“地理区域”的查询包含此句点,但我对 elasticsearch 查询有些困惑。
我仍然没有正确理解为了执行这些操作我的文档必须具有的结构,在这里我离开我正在调用的文档的类
@Data
@Document(indexName = "geozona")
public class GeozonaElasticDTO {
@Id
@Field(type = FieldType.Long)
private long id;
@Field(type = FieldType.Text)
private UUID uuid;
@Field(type = FieldType.Text)
private String nombre;
@Field(type = FieldType.Text)
private String descripcion;
private List<UUID> etiquetas;
private List<UUID> lugares;
private List<UUID> geozonaLimiteVeLocidad;
@Field(type = FieldType.Text)
private EnumTipoGeozona tipoGeozona;
@Field(type = FieldType.Double)
private Double radio;
@Field(type = FieldType.Text)
private String pathEncode;
@Field(type = FieldType.Object)
@GeoPointField
private List<GeoPoint> points;
@Field(type = FieldType.Double)
private double puntoDeReferenciaLatitud;
@Field(type = FieldType.Double)
private double puntoDeReferenciaLongitud;
@Field(type = FieldType.Integer)
private int limiteDeOrientacionGradoInicio;
@Field(type = FieldType.Integer)
private int limiteDeOrientacionGradoTermino;
@Field(type = FieldType.Integer)
private Integer ancho;
@Field(type = FieldType.Boolean)
private boolean eliminado;
@Field(type = FieldType.Date,format = DateFormat.custom,pattern = "uuuu-MM-dd''T''HH:mm:ssZ")
private zoneddatetime fechaCreacion;
@Field(type = FieldType.Date,pattern = "uuuu-MM-dd''T''HH:mm:ssZ")
private zoneddatetime fechaActualizacion;
@Field(type = FieldType.Integer)
private int version;
}
这是我在弹性服务器中的类的结构
"geozona": {
"aliases": {},"mappings": {
"properties": {
"_class": {
"type": "text","fields": {
"keyword": {
"type": "keyword","ignore_above": 256
}
}
},"ancho": {
"type": "integer"
},"descripcion": {
"type": "text"
},"eliminado": {
"type": "boolean"
},"etiquetas": {
"type": "text","fechaActualizacion": {
"type": "date","format": "uuuu-MM-dd''T''HH:mm:ssZ"
},"fechaCreacion": {
"type": "date","geozonaLimiteVeLocidad": {
"type": "text","id": {
"type": "keyword"
},"limiteDeOrientacionGradoInicio": {
"type": "integer"
},"limiteDeOrientacionGradoTermino": {
"type": "integer"
},"lugares": {
"type": "text","nombre": {
"type": "text"
},"pathEncode": {
"type": "text"
},"points": {
"type": "geo_point"
},"puntoDeReferenciaLatitud": {
"type": "double"
},"puntoDeReferenciaLongitud": {
"type": "double"
},"radio": {
"type": "double"
},"tipoGeozona": {
"type": "text"
},"uuid": {
"type": "text"
},"version": {
"type": "integer"
}
}
},"settings": {
"index": {
"refresh_interval": "1s","number_of_shards": "1","provided_name": "geozona","creation_date": "1609949683125","store": {
"type": "fs"
},"number_of_replicas": "1","uuid": "m-y7Qa5wSwGmDA3TVm4HkA","version": {
"created": "7090299"
}
}
}
}
}
如果有人能指导我如何开始正确处理地理定位点与弹性的重合,那将对我有很大帮助。
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)
ElasticSearch - 学习笔记 02-springboot 整合 jestclient 操作 elasticSearch


<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.16.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.huarui</groupId>
<artifactId>sb_elasticsearch_jestclient</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>sb_elasticsearch_jestclient</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>io.searchbox</groupId>
<artifactId>jest</artifactId>
<version>5.3.3</version>
</dependency>
<dependency>
<groupId>org.elasticsearch</groupId>
<artifactId>elasticsearch</artifactId>
<version>5.6.7</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
<repositories>
<repository>
<id>spring-snapshots</id>
<name>Spring Snapshots</name>
<url>https://repo.spring.io/snapshot</url>
<snapshots>
<enabled>true</enabled>
</snapshots>
</repository>
<repository>
<id>spring-milestones</id>
<name>Spring Milestones</name>
<url>https://repo.spring.io/milestone</url>
</repository>
</repositories>
<pluginRepositories>
<pluginRepository>
<id>spring-snapshots</id>
<name>Spring Snapshots</name>
<url>https://repo.spring.io/snapshot</url>
<snapshots>
<enabled>true</enabled>
</snapshots>
</pluginRepository>
<pluginRepository>
<id>spring-milestones</id>
<name>Spring Milestones</name>
<url>https://repo.spring.io/milestone</url>
</pluginRepository>
</pluginRepositories>
</project>
<dependency>
<groupId>io.searchbox</groupId>
<artifactId>jest</artifactId>
<version>5.3.3</version>
</dependency>
<dependency>
<groupId>org.elasticsearch</groupId>
<artifactId>elasticsearch</artifactId>
<version>5.6.7</version>
</dependency>
spring.elasticsearch.jest.uris = http://192.168.79.129:9200/
spring.elasticsearch.jest.read-timeout = 10000
spring.elasticsearch.jest.username =
spring.elasticsearch.jest.password =
junit
import com.huarui.entity.User;
import io.searchbox.client.JestClient;
import io.searchbox.client.JestResult;
import io.searchbox.core.*;
import io.searchbox.indices.CreateIndex;
import io.searchbox.indices.DeleteIndex;
import io.searchbox.indices.mapping.GetMapping;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
@RunWith(SpringRunner.class)
@SpringBootTest
public class ElasticApplicationTests {
private static String indexName = "userindex";
private static String typeName = "user";
@Autowired
JestClient jestClient;
/**
* 新增数据
* @return
* @throws Exception
*/
@Test
public void insert() throws Exception {
User user = new User(1L, "张三", 20, "张三是个Java开发工程师","2018-4-25 11:07:42");
Index index = new Index.Builder(user).index(indexName).type(typeName).build();
try{
JestResult jr = jestClient.execute(index);
System.out.println(jr.isSucceeded());
}catch(IOException e){
e.printStackTrace();
}
}
}
今天关于如何使用Elastic Java Client与AWS Elasticsearch Service对话?和elasticsearch客户端 java的讲解已经结束,谢谢您的阅读,如果想了解更多关于amazon-web-services – Elastic Beanstalk上的ElasticSearch、com.amazonaws.services.elasticbeanstalk.AWSElasticBeanstalkClient的实例源码、Elasticsearch - 如何在java中使用elasticsearch查找与地理定位点的匹配项、ElasticSearch - 学习笔记 02-springboot 整合 jestclient 操作 elasticSearch的相关知识,请在本站搜索。
本文标签: