SparkSql篇2:SparkSql读写elasticsearch
废话不多说,直接上干货
<dependency>
<groupId>org.elasticsearch</groupId>
<artifactId>elasticsearch-spark-20_2.11</artifactId>
<version>${es.version}</version>
</dependency>
1 RDD 操作ES:
import org.elasticsearch.spark._
读:
//Es昨日数据查询的json语句
val match_oneday=
s"""
|{
| "query": {
| "bool": {
| "must": [
| {
| "range": {
| "txsj": {
| "gte": $yesterDayStartLong,
| "lte": $yesterDayEndLong
| }
| }
| }
| ]
| }
| }
|}
""".stripMargin
// 获取 _.1 是key 就是ES的_id, _.2 就是value
val value: RDD[String,String] = sparkSession.sparkContext.esRDD("xyrxjl/caputre",match_oneday)
写:
EsSpark.saveToEs(value,s"bigdata_user_profile/user_profile",Map("es.mapping.id"->"user_id")) //指定Es的_id= user_id,保证数据的幂等性
EsSpark.saveToEs(value,s"bigdata_user_profile/user_profile") //自动生成Es的_id
2 DaraFrame操作ES:
import org.elasticsearch.spark.sql._
读:
// 查询Es所有数据的Json语句
val match_all =
"""| {"query":{"match_all":{}}}
""".stripMargin
// 直接获取value转成DF,在准成列式存储的内存表
val value:DataFrame={sparkSession.esDF("bigdata_user_profile/user_profile",match_all)}
value.createOrReplaceTempView("t_value") //把value转成临时表
写:
EsSparkSQL.saveToEs(dataKudu,s"bigdata_user_profile/user_profile",Map("es.mapping.id"->"user_id")) //指定Es的_id= user_id,保证数据的幂等性
EsSparkSQL.saveToEs(dataKudu,s"bigdata_user_profile/user_profile") //自动生成Es的_id
3 Spark操作Es的参数调优:
--conf spark.es.nodes="10.24.74.10:9200" \
--conf spark.es.index.auto.create="true" \
--conf spark.es.write.operation="index" \
--conf spark.es.scroll.size=5000 \
--conf spark.es.input.use.sliced.partitions=false \
--conf spark.es.batch.size.entries=5000 \
--conf spark.es.batch.write.refresh=false \
--conf spark.es.batch.size.bytes="5mb" \
--conf spark.es.nodes.wan.only="true"