首页 文章 精选 留言 我的

精选列表

搜索[API增强],共10000篇文章
优秀的个人博客,低调大师

Spark RDD/Core 编程 API入门系列 之rdd案例(map、filter、flatMap、groupByKey、reduceB...

声明: 大数据中,最重要的算子操作是:join !!! 典型的transformation和action val nums = sc.parallelize(1 to 10) //根据集合创建RDD map适用于 package com.zhouls.spark.cores import org.apache.spark.{SparkConf, SparkContext} /** * Created by Administrator on 2016/9/27. */ object Transformations { def main(args: Array[String]) { val conf = new SparkConf().setAppName("Transformations").setMaster("local") val sc = new SparkContext(conf) val nums = sc.parallelize(1 to 10) //根据集合创建RDD val mapped = nums.map(item => 2 + item) mapped.collect.foreach(println) } }map源码 /** * Return a new RDD by applying a function to all elements of this RDD. */ def map[U: ClassTag](f: T => U): RDD[U] = withScope { val cleanF = sc.clean(f) new MapPartitionsRDD[U, T](this, (context, pid, iter) => iter.map(cleanF)) } filter适用于 package com.zhouls.spark.cores import org.apache.spark.{SparkConf, SparkContext} /** * Created by Administrator on 2016/9/27. */ object Transformations { def main(args: Array[String]) { val conf = new SparkConf().setAppName("Transformations").setMaster("local") val sc = new SparkContext(conf) val nums = sc.parallelize(1 to 10) //根据集合创建RDD val mapped = nums.map(item => 2 + item) val filtered = nums.filter(item => item%2 == 0) filtered.collect.foreach(println) } } filter源码 /** * Return a new RDD containing only the elements that satisfy a predicate. */ def filter(f: T => Boolean): RDD[T] = withScope { val cleanF = sc.clean(f) new MapPartitionsRDD[T, T]( this, (context, pid, iter) => iter.filter(cleanF), preservesPartitioning = true) } flatMap适用于 package com.zhouls.spark.cores import org.apache.spark.{SparkConf, SparkContext} /** * Created by Administrator on 2016/9/27. */ object Transformations { def main(args: Array[String]) { val conf = new SparkConf().setAppName("Transformations").setMaster("local") val sc = new SparkContext(conf) val nums = sc.parallelize(1 to 10) //根据集合创建RDD val mapped = nums.map(item => 2 + item) // mapped.collect.foreach(println) val filtered = nums.filter(item => item%2 == 0) // filtered.collect.foreach(println) val bigData = Array("Scala Spark","Java Hadoop","Java Tachyon") val bigDataString = sc.parallelize(bigData) val words = bigDataString.flatMap(line => line.split(" ")) words.collect.foreach(println) sc.stop() } } flatMap源码 /** * Return a new RDD by first applying a function to all elements of this * RDD, and then flattening the results. */ def flatMap[U: ClassTag](f: T => TraversableOnce[U]): RDD[U] = withScope { val cleanF = sc.clean(f) new MapPartitionsRDD[U, T](this, (context, pid, iter) => iter.flatMap(cleanF)) } 成为大牛,必写的写法 -> groupByKey适用于 package com.zhouls.spark.cores import org.apache.spark.{SparkConf, SparkContext} /** * Created by Administrator on 2016/9/27. */ object Transformations { def main(args: Array[String]) { val sc = sparkContext("Transformations Operations") //创建SparkContext // mapTransformation(sc)//map案例 // filterTransformation(sc)//filter案例 // flatMapTransformation(sc)//flatMap案例 groupByKeyTransformation(sc) sc.stop() //停止sparkContext,释放相关的Driver对象,释放资源 } def sparkContext(name:String)={ val conf = new SparkConf().setAppName("Transformations").setMaster("local") val sc = new SparkContext(conf) sc } def mapTransformation(sc:SparkContext){ val nums = sc.parallelize(1 to 10) //根据集合创建RDD val mapped = nums.map(item => 2 * item) //map适用于任何类型的元素且对其作用的集合中的每一个元素循环遍历并调用其作为参数的函数对每一个遍历的元素进行具体化处理 mapped.collect.foreach(println)//收集计算结果并通过foreach循环打印 } def filterTransformation(sc:SparkContext){ val nums = sc.parallelize(1 to 20) //根据集合创建RDD val filtered = nums.filter(item => item%2 == 0)//根据filter中作为参数的函数Boolean来判断符合条件的元素,并基于这些元素构成新的MapPartitionsRDD。 filtered.collect.foreach(println)//收集计算结果并通过foreach循环打印 } def flatMapTransformation(sc:SparkContext){ val bigData = Array("Scala Spark","Java Hadoop","Java Tachyon")//实例化字符串类型的Array val bigDataString = sc.parallelize(bigData)//创建以字符串为元素类型的MapPartitionsRDD val words = bigDataString.flatMap(line => line.split(" "))//首先是通过传入的作为参数的函数来作用于RDD的每个字符串进行单词切分(是以集合的方式存在的),然后把切分后的结果合并成一个大的集合,是{Scala Spark Java Hadoop Java Tachyon} words.collect.foreach(println)//收集计算结果并通过foreach循环打印 } def groupByKeyTransformation(sc:SparkContext){ val data = Array(Tuple2(100,"Spark"),Tuple2(100,"Tachyon"),Tuple2(70,"Hadoop"),Tuple2(80,"Kafka"),Tuple2(80,"HBase")) val dataRDD = sc.parallelize(data) val grouped = dataRDD.groupByKey() grouped.collect.foreach(println)//收集计算结果并通过foreach循环打印 } } groupByKey源码 ** * Group the values for each key in the RDD into a single sequence. Allows controlling the * partitioning of the resulting key-value pair RDD by passing a Partitioner. * The ordering of elements within each group is not guaranteed, and may even differ * each time the resulting RDD is evaluated. * * Note: This operation may be very expensive. If you are grouping in order to perform an * aggregation (such as a sum or average) over each key, using [[PairRDDFunctions.aggregateByKey]] * or [[PairRDDFunctions.reduceByKey]] will provide much better performance. * * Note: As currently implemented, groupByKey must be able to hold all the key-value pairs for any * key in memory. If a key has too many values, it can result in an [[OutOfMemoryError]]. */ def groupByKey(partitioner: Partitioner): RDD[(K, Iterable[V])] = self.withScope { // groupByKey shouldn't use map side combine because map side combine does not // reduce the amount of data shuffled and requires all map side data be inserted // into a hash table, leading to more objects in the old gen. val createCombiner = (v: V) => CompactBuffer(v) val mergeValue = (buf: CompactBuffer[V], v: V) => buf += v val mergeCombiners = (c1: CompactBuffer[V], c2: CompactBuffer[V]) => c1 ++= c2 val bufs = combineByKey[CompactBuffer[V]]( createCombiner, mergeValue, mergeCombiners, partitioner, mapSideCombine = false) bufs.asInstanceOf[RDD[(K, Iterable[V])]] } /** * Group the values for each key in the RDD into a single sequence. Hash-partitions the * resulting RDD with into `numPartitions` partitions. The ordering of elements within * each group is not guaranteed, and may even differ each time the resulting RDD is evaluated. * * Note: This operation may be very expensive. If you are grouping in order to perform an * aggregation (such as a sum or average) over each key, using [[PairRDDFunctions.aggregateByKey]] * or [[PairRDDFunctions.reduceByKey]] will provide much better performance. * * Note: As currently implemented, groupByKey must be able to hold all the key-value pairs for any * key in memory. If a key has too many values, it can result in an [[OutOfMemoryError]]. */ def groupByKey(numPartitions: Int): RDD[(K, Iterable[V])] = self.withScope { groupByKey(new HashPartitioner(numPartitions)) } reduceByKey适用于 package com.zhouls.spark.cores import org.apache.spark.{SparkConf, SparkContext} /** * Created by Administrator on 2016/9/27. */ object Transformations { def main(args: Array[String]) { val sc = sparkContext("Transformations Operations") //创建SparkContext // mapTransformation(sc)//map案例 // filterTransformation(sc)//filter案例 // flatMapTransformation(sc)//flatMap案例 // groupByKeyTransformation(sc)//groupByKey案例 reduceByKeyTransformation(sc)//reduceByKey案例 sc.stop() //停止sparkContext,释放相关的Driver对象,释放资源 } def sparkContext(name:String)={ val conf = new SparkConf().setAppName("Transformations").setMaster("local") val sc = new SparkContext(conf) sc } def mapTransformation(sc:SparkContext){ val nums = sc.parallelize(1 to 10) //根据集合创建RDD val mapped = nums.map(item => 2 * item) //map适用于任何类型的元素且对其作用的集合中的每一个元素循环遍历并调用其作为参数的函数对每一个遍历的元素进行具体化处理 mapped.collect.foreach(println)//收集计算结果并通过foreach循环打印 } def filterTransformation(sc:SparkContext){ val nums = sc.parallelize(1 to 20) //根据集合创建RDD val filtered = nums.filter(item => item%2 == 0)//根据filter中作为参数的函数Boolean来判断符合条件的元素,并基于这些元素构成新的MapPartitionsRDD。 filtered.collect.foreach(println)//收集计算结果并通过foreach循环打印 } def flatMapTransformation(sc:SparkContext){ val bigData = Array("Scala Spark","Java Hadoop","Java Tachyon")//实例化字符串类型的Array val bigDataString = sc.parallelize(bigData)//创建以字符串为元素类型的MapPartitionsRDD val words = bigDataString.flatMap(line => line.split(" "))//首先是通过传入的作为参数的函数来作用于RDD的每个字符串进行单词切分(是以集合的方式存在的),然后把切分后的结果合并成一个大的集合,是{Scala Spark Java Hadoop Java Tachyon} words.collect.foreach(println)//收集计算结果并通过foreach循环打印 } def groupByKeyTransformation(sc:SparkContext){ val data = Array(Tuple2(100,"Spark"),Tuple2(100,"Tachyon"),Tuple2(70,"Hadoop"),Tuple2(80,"Kafka"),Tuple2(80,"HBase"))//准备数据 val dataRDD = sc.parallelize(data)//根据集合创建RDD val grouped = dataRDD.groupByKey()//按照相同的key对value进行分组,分组后的value是一个集合 grouped.collect.foreach(println)//收集计算结果并通过foreach循环打印 } def reduceByKeyTransformation(sc:SparkContext){ val lines = sc.textFile("D://SoftWare//spark-1.6.2-bin-hadoop2.6//README.md") val words = lines.flatMap{ line => line.split(" ")} val pairs = words.map { word => (word,1) } val wordCountsOdered = pairs.reduceByKey(_+_)//对相同的key,进行value的累计(包括local和reducer级别同时reduce) wordCountsOdered.collect.foreach(wordNumberPair => println(wordNumberPair._1 + ":" + wordNumberPair._2))//收集计算结果并通过foreach循环打印 } } reduceByKey源码 /** * Merge the values for each key using an associative reduce function. This will also perform * the merging locally on each mapper before sending results to a reducer, similarly to a * "combiner" in MapReduce. Output will be hash-partitioned with the existing partitioner/ * parallelism level. */ def reduceByKey(func: (V, V) => V): RDD[(K, V)] = self.withScope { reduceByKey(defaultPartitioner(self), func) } join适用于 package com.zhouls.spark.cores import org.apache.spark.{SparkConf, SparkContext} /** * Created by Administrator on 2016/9/27. */ object Transformations { def main(args: Array[String]) { val sc = sparkContext("Transformations Operations") //创建SparkContext // mapTransformation(sc)//map案例 // filterTransformation(sc)//filter案例 // flatMapTransformation(sc)//flatMap案例 // groupByKeyTransformation(sc)//groupByKey案例 // reduceByKeyTransformation(sc)//reduceByKey案例 joinTransformation(sc)//join案例 sc.stop() //停止sparkContext,释放相关的Driver对象,释放资源 } def sparkContext(name:String)={ val conf = new SparkConf().setAppName("Transformations").setMaster("local") val sc = new SparkContext(conf) sc } def mapTransformation(sc:SparkContext){ val nums = sc.parallelize(1 to 10) //根据集合创建RDD val mapped = nums.map(item => 2 * item) //map适用于任何类型的元素且对其作用的集合中的每一个元素循环遍历并调用其作为参数的函数对每一个遍历的元素进行具体化处理 mapped.collect.foreach(println)//收集计算结果并通过foreach循环打印 } def filterTransformation(sc:SparkContext){ val nums = sc.parallelize(1 to 20) //根据集合创建RDD val filtered = nums.filter(item => item%2 == 0)//根据filter中作为参数的函数Boolean来判断符合条件的元素,并基于这些元素构成新的MapPartitionsRDD。 filtered.collect.foreach(println)//收集计算结果并通过foreach循环打印 } def flatMapTransformation(sc:SparkContext){ val bigData = Array("Scala Spark","Java Hadoop","Java Tachyon")//实例化字符串类型的Array val bigDataString = sc.parallelize(bigData)//创建以字符串为元素类型的MapPartitionsRDD val words = bigDataString.flatMap(line => line.split(" "))//首先是通过传入的作为参数的函数来作用于RDD的每个字符串进行单词切分(是以集合的方式存在的),然后把切分后的结果合并成一个大的集合,是{Scala Spark Java Hadoop Java Tachyon} words.collect.foreach(println)//收集计算结果并通过foreach循环打印 } def groupByKeyTransformation(sc:SparkContext){ val data = Array(Tuple2(100,"Spark"),Tuple2(100,"Tachyon"),Tuple2(70,"Hadoop"),Tuple2(80,"Kafka"),Tuple2(80,"HBase"))//准备数据 val dataRDD = sc.parallelize(data)//根据集合创建RDD val grouped = dataRDD.groupByKey()//按照相同的key对value进行分组,分组后的value是一个集合 grouped.collect.foreach(println)//收集计算结果并通过foreach循环打印 } def reduceByKeyTransformation(sc:SparkContext){ val lines = sc.textFile("D://SoftWare//spark-1.6.2-bin-hadoop2.6//README.md") val words = lines.flatMap{ line => line.split(" ")} val pairs = words.map { word => (word,1) } val wordCountsOdered = pairs.reduceByKey(_+_)//对相同的key,进行value的累计(包括local和reducer级别同时reduce) wordCountsOdered.collect.foreach(wordNumberPair => println(wordNumberPair._1 + ":" + wordNumberPair._2))//收集计算结果并通过foreach循环打印 } def joinTransformation(sc:SparkContext){ val studentNames = Array(Tuple2(1,"Spark"),Tuple2(2,"Tachyon"),Tuple2(3,"Hadoop")) val studentScores = Array(Tuple2(1,100),Tuple2(2,95),Tuple2(3,65)) val names = sc.parallelize(studentNames) val scores = sc.parallelize(studentScores) val studentNamesAndScores = names.join(scores) studentNamesAndScores.collect.foreach(println)//收集计算结果并通过foreach循环打印 } } join源码 /** * Cartesian join with another [[DataFrame]]. * * Note that cartesian joins are very expensive without an extra filter that can be pushed down. * * @param right Right side of the join operation. * @group dfops * @since 1.3.0 */ def join(right: DataFrame): DataFrame = { Join(logicalPlan, right.logicalPlan, joinType = Inner, None) } /** * Inner equi-join with another [[DataFrame]] using the given column. * * Different from other join functions, the join column will only appear once in the output, * i.e. similar to SQL's `JOIN USING` syntax. * * {{{ * // Joining df1 and df2 using the column "user_id" * df1.join(df2, "user_id") * }}} * * Note that if you perform a self-join using this function without aliasing the input * [[DataFrame]]s, you will NOT be able to reference any columns after the join, since * there is no way to disambiguate which side of the join you would like to reference. * * @param right Right side of the join operation. * @param usingColumn Name of the column to join on. This column must exist on both sides. * @group dfops * @since 1.4.0 */ def join(right: DataFrame, usingColumn: String): DataFrame = { join(right, Seq(usingColumn)) } /** * Inner equi-join with another [[DataFrame]] using the given columns. * * Different from other join functions, the join columns will only appear once in the output, * i.e. similar to SQL's `JOIN USING` syntax. * * {{{ * // Joining df1 and df2 using the columns "user_id" and "user_name" * df1.join(df2, Seq("user_id", "user_name")) * }}} * * Note that if you perform a self-join using this function without aliasing the input * [[DataFrame]]s, you will NOT be able to reference any columns after the join, since * there is no way to disambiguate which side of the join you would like to reference. * * @param right Right side of the join operation. * @param usingColumns Names of the columns to join on. This columns must exist on both sides. * @group dfops * @since 1.4.0 */ def join(right: DataFrame, usingColumns: Seq[String]): DataFrame = { // Analyze the self join. The assumption is that the analyzer will disambiguate left vs right // by creating a new instance for one of the branch. val joined = sqlContext.executePlan( Join(logicalPlan, right.logicalPlan, joinType = Inner, None)).analyzed.asInstanceOf[Join] // Project only one of the join columns. val joinedCols = usingColumns.map(col => joined.right.resolve(col)) val condition = usingColumns.map { col => catalyst.expressions.EqualTo(joined.left.resolve(col), joined.right.resolve(col)) }.reduceLeftOption[catalyst.expressions.BinaryExpression] { (cond, eqTo) => catalyst.expressions.And(cond, eqTo) } Project( joined.output.filterNot(joinedCols.contains(_)), Join( joined.left, joined.right, joinType = Inner, condition) ) } /** * Inner join with another [[DataFrame]], using the given join expression. * * {{{ * // The following two are equivalent: * df1.join(df2, $"df1Key" === $"df2Key") * df1.join(df2).where($"df1Key" === $"df2Key") * }}} * @group dfops * @since 1.3.0 */ def join(right: DataFrame, joinExprs: Column): DataFrame = join(right, joinExprs, "inner") /** * Join with another [[DataFrame]], using the given join expression. The following performs * a full outer join between `df1` and `df2`. * * {{{ * // Scala: * import org.apache.spark.sql.functions._ * df1.join(df2, $"df1Key" === $"df2Key", "outer") * * // Java: * import static org.apache.spark.sql.functions.*; * df1.join(df2, col("df1Key").equalTo(col("df2Key")), "outer"); * }}} * * @param right Right side of the join. * @param joinExprs Join expression. * @param joinType One of: `inner`, `outer`, `left_outer`, `right_outer`, `leftsemi`. * @group dfops * @since 1.3.0 */ def join(right: DataFrame, joinExprs: Column, joinType: String): DataFrame = { // Note that in this function, we introduce a hack in the case of self-join to automatically // resolve ambiguous join conditions into ones that might make sense [SPARK-6231]. // Consider this case: df.join(df, df("key") === df("key")) // Since df("key") === df("key") is a trivially true condition, this actually becomes a // cartesian join. However, most likely users expect to perform a self join using "key". // With that assumption, this hack turns the trivially true condition into equality on join // keys that are resolved to both sides. // Trigger analysis so in the case of self-join, the analyzer will clone the plan. // After the cloning, left and right side will have distinct expression ids. val plan = Join(logicalPlan, right.logicalPlan, JoinType(joinType), Some(joinExprs.expr)) .queryExecution.analyzed.asInstanceOf[Join] // If auto self join alias is disabled, return the plan. if (!sqlContext.conf.dataFrameSelfJoinAutoResolveAmbiguity) { return plan } // If left/right have no output set intersection, return the plan. val lanalyzed = this.logicalPlan.queryExecution.analyzed val ranalyzed = right.logicalPlan.queryExecution.analyzed if (lanalyzed.outputSet.intersect(ranalyzed.outputSet).isEmpty) { return plan } // Otherwise, find the trivially true predicates and automatically resolves them to both sides. // By the time we get here, since we have already run analysis, all attributes should've been // resolved and become AttributeReference. val cond = plan.condition.map { _.transform { case catalyst.expressions.EqualTo(a: AttributeReference, b: AttributeReference) if a.sameRef(b) => catalyst.expressions.EqualTo(plan.left.resolve(a.name), plan.right.resolve(b.name)) }} plan.copy(condition = cond) } cogroup的scala版,适用于 package com.zhouls.spark.cores import org.apache.spark.{SparkConf, SparkContext} /** * Created by Administrator on 2016/9/27. */ object Transformations { def main(args: Array[String]) { val sc = sparkContext("Transformations Operations") //创建SparkContext // mapTransformation(sc)//map案例 // filterTransformation(sc)//filter案例 // flatMapTransformation(sc)//flatMap案例 // groupByKeyTransformation(sc)//groupByKey案例 // reduceByKeyTransformation(sc)//reduceByKey案例 // joinTransformation(sc)//join案例 cogroupTransformation(sc)//cogroup案例 sc.stop() //停止sparkContext,释放相关的Driver对象,释放资源 } def sparkContext(name:String)={ val conf = new SparkConf().setAppName("Transformations").setMaster("local") val sc = new SparkContext(conf) sc } def mapTransformation(sc:SparkContext){ val nums = sc.parallelize(1 to 10) //根据集合创建RDD val mapped = nums.map(item => 2 * item) //map适用于任何类型的元素且对其作用的集合中的每一个元素循环遍历并调用其作为参数的函数对每一个遍历的元素进行具体化处理 mapped.collect.foreach(println)//收集计算结果并通过foreach循环打印 } def filterTransformation(sc:SparkContext){ val nums = sc.parallelize(1 to 20) //根据集合创建RDD val filtered = nums.filter(item => item%2 == 0)//根据filter中作为参数的函数Boolean来判断符合条件的元素,并基于这些元素构成新的MapPartitionsRDD。 filtered.collect.foreach(println)//收集计算结果并通过foreach循环打印 } def flatMapTransformation(sc:SparkContext){ val bigData = Array("Scala Spark","Java Hadoop","Java Tachyon")//实例化字符串类型的Array val bigDataString = sc.parallelize(bigData)//创建以字符串为元素类型的MapPartitionsRDD val words = bigDataString.flatMap(line => line.split(" "))//首先是通过传入的作为参数的函数来作用于RDD的每个字符串进行单词切分(是以集合的方式存在的),然后把切分后的结果合并成一个大的集合,是{Scala Spark Java Hadoop Java Tachyon} words.collect.foreach(println)//收集计算结果并通过foreach循环打印 } def groupByKeyTransformation(sc:SparkContext){ val data = Array(Tuple2(100,"Spark"),Tuple2(100,"Tachyon"),Tuple2(70,"Hadoop"),Tuple2(80,"Kafka"),Tuple2(80,"HBase"))//准备数据 val dataRDD = sc.parallelize(data)//根据集合创建RDD val grouped = dataRDD.groupByKey()//按照相同的key对value进行分组,分组后的value是一个集合 grouped.collect.foreach(println)//收集计算结果并通过foreach循环打印 } def reduceByKeyTransformation(sc:SparkContext){ val lines = sc.textFile("D://SoftWare//spark-1.6.2-bin-hadoop2.6//README.md") val words = lines.flatMap{ line => line.split(" ")} val pairs = words.map { word => (word,1) } val wordCountsOdered = pairs.reduceByKey(_+_)//对相同的key,进行value的累计(包括local和reducer级别同时reduce) wordCountsOdered.collect.foreach(wordNumberPair => println(wordNumberPair._1 + ":" + wordNumberPair._2))//收集计算结果并通过foreach循环打印 } def joinTransformation(sc:SparkContext){ val studentNames = Array(Tuple2(1,"Spark"),Tuple2(2,"Tachyon"),Tuple2(3,"Hadoop")) val studentScores = Array(Tuple2(1,100),Tuple2(2,95),Tuple2(3,65)) val names = sc.parallelize(studentNames) val scores = sc.parallelize(studentScores) val studentNamesAndScores = names.join(scores) studentNamesAndScores.collect.foreach(println)//收集计算结果并通过foreach循环打印 } def cogroupTransformation(sc:SparkContext){ val namesLists = Array(Tuple2(1,"xiaoming"),Tuple2(2,"xiaozhou"),Tuple2(3,"xiaoliu")) val scoresLists = Array(Tuple2(1,100),Tuple2(2,95),Tuple2(3,85),Tuple2(1,75),Tuple2(2,65),Tuple2(3,55)) val names = sc.parallelize(namesLists) val scores = sc.parallelize(scoresLists) val namesListsAndScores = names.cogroup(scores) namesListsAndScores.collect.foreach(println)//收集计算结果并通过foreach循环打印 } } cogroup源码 /** * For each key k in `this` or `other1` or `other2` or `other3`, * return a resulting RDD that contains a tuple with the list of values * for that key in `this`, `other1`, `other2` and `other3`. */ def cogroup[W1, W2, W3](other1: RDD[(K, W1)], other2: RDD[(K, W2)], other3: RDD[(K, W3)], partitioner: Partitioner) : RDD[(K, (Iterable[V], Iterable[W1], Iterable[W2], Iterable[W3]))] = self.withScope { if (partitioner.isInstanceOf[HashPartitioner] && keyClass.isArray) { throw new SparkException("Default partitioner cannot partition array keys.") } val cg = new CoGroupedRDD[K](Seq(self, other1, other2, other3), partitioner) cg.mapValues { case Array(vs, w1s, w2s, w3s) => (vs.asInstanceOf[Iterable[V]], w1s.asInstanceOf[Iterable[W1]], w2s.asInstanceOf[Iterable[W2]], w3s.asInstanceOf[Iterable[W3]]) } } /** * For each key k in `this` or `other`, return a resulting RDD that contains a tuple with the * list of values for that key in `this` as well as `other`. */ def cogroup[W](other: RDD[(K, W)], partitioner: Partitioner) : RDD[(K, (Iterable[V], Iterable[W]))] = self.withScope { if (partitioner.isInstanceOf[HashPartitioner] && keyClass.isArray) { throw new SparkException("Default partitioner cannot partition array keys.") } val cg = new CoGroupedRDD[K](Seq(self, other), partitioner) cg.mapValues { case Array(vs, w1s) => (vs.asInstanceOf[Iterable[V]], w1s.asInstanceOf[Iterable[W]]) } } /** * For each key k in `this` or `other1` or `other2`, return a resulting RDD that contains a * tuple with the list of values for that key in `this`, `other1` and `other2`. */ def cogroup[W1, W2](other1: RDD[(K, W1)], other2: RDD[(K, W2)], partitioner: Partitioner) : RDD[(K, (Iterable[V], Iterable[W1], Iterable[W2]))] = self.withScope { if (partitioner.isInstanceOf[HashPartitioner] && keyClass.isArray) { throw new SparkException("Default partitioner cannot partition array keys.") } val cg = new CoGroupedRDD[K](Seq(self, other1, other2), partitioner) cg.mapValues { case Array(vs, w1s, w2s) => (vs.asInstanceOf[Iterable[V]], w1s.asInstanceOf[Iterable[W1]], w2s.asInstanceOf[Iterable[W2]]) } } /** * For each key k in `this` or `other1` or `other2` or `other3`, * return a resulting RDD that contains a tuple with the list of values * for that key in `this`, `other1`, `other2` and `other3`. */ def cogroup[W1, W2, W3](other1: RDD[(K, W1)], other2: RDD[(K, W2)], other3: RDD[(K, W3)]) : RDD[(K, (Iterable[V], Iterable[W1], Iterable[W2], Iterable[W3]))] = self.withScope { cogroup(other1, other2, other3, defaultPartitioner(self, other1, other2, other3)) } /** * For each key k in `this` or `other`, return a resulting RDD that contains a tuple with the * list of values for that key in `this` as well as `other`. */ def cogroup[W](other: RDD[(K, W)]): RDD[(K, (Iterable[V], Iterable[W]))] = self.withScope { cogroup(other, defaultPartitioner(self, other)) } /** * For each key k in `this` or `other1` or `other2`, return a resulting RDD that contains a * tuple with the list of values for that key in `this`, `other1` and `other2`. */ def cogroup[W1, W2](other1: RDD[(K, W1)], other2: RDD[(K, W2)]) : RDD[(K, (Iterable[V], Iterable[W1], Iterable[W2]))] = self.withScope { cogroup(other1, other2, defaultPartitioner(self, other1, other2)) } /** * For each key k in `this` or `other`, return a resulting RDD that contains a tuple with the * list of values for that key in `this` as well as `other`. */ def cogroup[W]( other: RDD[(K, W)], numPartitions: Int): RDD[(K, (Iterable[V], Iterable[W]))] = self.withScope { cogroup(other, new HashPartitioner(numPartitions)) } /** * For each key k in `this` or `other1` or `other2`, return a resulting RDD that contains a * tuple with the list of values for that key in `this`, `other1` and `other2`. */ def cogroup[W1, W2](other1: RDD[(K, W1)], other2: RDD[(K, W2)], numPartitions: Int) : RDD[(K, (Iterable[V], Iterable[W1], Iterable[W2]))] = self.withScope { cogroup(other1, other2, new HashPartitioner(numPartitions)) } /** * For each key k in `this` or `other1` or `other2` or `other3`, * return a resulting RDD that contains a tuple with the list of values * for that key in `this`, `other1`, `other2` and `other3`. */ def cogroup[W1, W2, W3](other1: RDD[(K, W1)], other2: RDD[(K, W2)], other3: RDD[(K, W3)], numPartitions: Int) : RDD[(K, (Iterable[V], Iterable[W1], Iterable[W2], Iterable[W3]))] = self.withScope { cogroup(other1, other2, other3, new HashPartitioner(numPartitions)) } 本文转自大数据躺过的坑博客园博客,原文链接:http://www.cnblogs.com/zlslch/p/5913846.html,如需转载请自行联系原作者

优秀的个人博客,低调大师

从 PHP 到 AI + Golang,程序员自救转型手记(四十九):多条件组筛选、字段白名单(增强功能并预防SQL注入)

这是一个系列 Blog,作者将以一个 PHP 全栈工程师的身份,利用 AI 工具(claude code、codex、deepseek、豆包等):从零开始学习 golang 语言,并最终完成 ai-go-admin([github](https://github.com/ai-go-hub/ai-go-admin) | [gitee](https://gitee.com/ai-go-hub/ai-go-admin))开源项目的制作,全程记录分享。 在上一期,我们进行了 “菜单规则管理实现”,本期将完成:多条件组筛选、字段白名单 # 筛选字段白名单 白名单说白了就是先在模型定义好所有字段,然后检查前端传递的 `筛选字段名称`,是否在模型定义内,否则就算字段不存在,主要是为了安全着想,避免 SQL 注入等。 之前我们在仓储层已经做好了 `检查一个字段是否在模型内` 的方法,而且 `排序字段名` 已经做过白名单检查了,之前没有做筛选字段的检查,主要是因为筛选功能还不完善。 这里直接让 AI,在服务层,使用 `检查一个字段是否在模型内` 方法,检查所有筛选条件提供的 `Field` 即可。 # 筛选操作符号白名单 众所周知,一个筛选条件的基本结构是这样的:`Where("name = ?", "jinzhu")`; 我们已经完成了字段名的检查,字段值则是直接使用 `?` 这种插值的语法,无需担心注入问题,那么操作符号(`=、>、 0 -- `,SQL `status = 1 or id > 0 -- ?`。 接下来就是如何优雅的实现操作符白名单,我们之前已经写了一个 `GetOperatorByAlias` 方法,用于将前端 `eq` 转为 `=`、`ne` 转为 `!=` 等,所以直接利用它,将所有允许的操作符号列出来就行了,不允许的返回空字符或者 nil,拼接 where 时,去掉 nil 的筛选条件即可。 # 多条件组筛选 目前支持的筛选条件数据是这样的: ```go type Where struct { Field string Operator string Value any } ``` 前端传递一个 `[]Where`,服务端将切片中的每一项组装为一个 `GORM` 的 `scope`,然后传递给仓储层使用,所以 `scopes` 直接的连接符号统一是 `AND`,比如: ```ts [ { field: 'a', operator: 'eq', value: '1', }, { field: 'b', operator: 'eq', value: '2', }, ] ``` 将组装为两个 `scope`,最终 SQL 类似:`WHERE a=1 AND b=2` 我希望实现,前端传递: ```ts [ {wheres: []Where, or: true}, {wheres: []Where, or: false}, ] ``` `wheres: []Where` 字段代表以前版本的筛选条件数据,而且保持数组格式,可以传递多个,而这些条件之间的连接符号,取用 `or` 字段的值,`true` 则使用 `OR`,否则使用 `AND`,示例如下: ```ts [ { wheres: [ { field: 'a', operator: 'eq', value: '1', }, { field: 'b', operator: 'eq', value: '2', }, ], or: true }, { wheres: [ { field: 'c', operator: 'eq', value: '3', }, { field: 'd', operator: 'eq', value: '4', }, ], or: false }, ] ``` 一个 `[]Where` 组装为一个 `GORM` 的 `scope`,最终 SQL 类似:`WHERE (a=1 OR b=2) AND (c=3 AND d=4)` 最终可以达成复杂查询下 `scopes` 减少,和单个 `scope` 内的多个筛选条件支持自定义 `OR / AND` 连接符号。 服务端支持了这种 `多条件组筛选` 后,前端的 `表格` 和 `远程下拉` 都会受益,因为它们就是基于服务端 `List` 方法获取数据的,而且不用担心安全问题,我们的字段名和操作符号都有白名单,值则是使用 `?` 插值语法天然防范 SQL 注入。

优秀的个人博客,低调大师

qKnow 知识平台商业版 2.1.0:语义检索增强,多视图知识图谱可视化与多图数据库适配全线升级

qKnow 知识平台商业版 2.1.0 是一次以“可用性、可观测性与智能化”为核心的系统级升级。我们重构了检索引擎,引入自然语言理解;扩展图谱渲染能力,支持多布局与多视图;补齐事件、字典、标签等知识管理能力;同时加入图数据库通用适配层,让系统能在 Neo4j 与 ArangoDB 之间无缝切换。 为什么需要 2.1.0? 在与政企客户、医药机构、工业制造用户的长期合作中,我们发现: 关键词检索太“死板”,错一个字就搜不到; 图谱布局单一,很难展示复杂关联; 客户想知道图谱到底有多少实体、多少关系,却没有统计页面; 知识智能检索不足,不支持自然语言; 不同行业客户使用不同图数据库,难以统一适配; 知识管理工具缺少事件、标签、字典等体系化能力。 qKnow 知识平台商业版 2.1.0 正是针对这些高频痛点进行的一次系统级进化。 本次更新的核心能力 1️⃣ 全面升级的知识管理能力 🟦 事件管理:让知识按时间“讲故事” 在新版中,事件成为一级知识对象。你可以新建“事件”,填写事件发生的时间、地点、参与实体等结构化字段。 让你可以: 在时间线里看到政策演变过程 查看某事件牵涉的机构、产品、人物 进行趋势推演、因果分析 🟩 字典管理:抽取更准确、展示更可读 例如:药品类型字段值为“0”“1”,通过字典可映射成“外用”“注射”,大幅提升可读性。 🟧 标签管理:高维实体的快速分类工具 为实体打标签,例如“药品”“器械”“企业”,可用于: 更快筛选实体 图谱中高亮某类实体 检索中精准定位目标对象 2️⃣ 单图谱统计:第一次真正了解你的图谱长什么样 全新的 “图谱概览” 页面提供完整的统计指标。 包括: 实体数 关系数 属性数 概念数 三元组总量 知识数量 抽取任务数 📸 截图示例:图谱概览界面展示多个统计卡片及趋势图,图谱规模一眼即可看清。 无论是给领导汇报、还是对知识质量做体检,这个页面都极其有用。 3️⃣ 多布局 + 多视图:怎么看得清就怎么用 🟦 多种布局模式 新版图谱支持: 力导向布局 网络布局 层次布局 环形布局 同心圆布局 MDS 布局 📸 截图示例:网络布局下的图谱展示更稠密、层级明晰,环形布局突出核心实体与外围关联。 你可以根据分析目的选择最合适的视图,让图谱从“看不清”变为“一看就懂”。 🟩 四种可切换视图模式 ① 常规视图 完整展示图谱结构,适合日常浏览。 ② 关系视图 强调“谁与谁有关”。 📸 截图示例:关系视图切换不同布局后,关系束、簇群结构清晰可见。 ③ 时序视图 事件根据时间顺序排列,适合政策演变、事故推演场景。 📸 截图示例:时间轴上事件卡片按时间点展示,点击事件自动高亮关联实体。 ④ 表格视图 以 Excel 风格展示实体、关系,适合检视与校对数据。 4️⃣ 新一代知识检索体系:从“查数据”进化为“问知识” 这是 2.1.0 最大的升级亮点。 ⭐ 语义检索:一句话就能搜(核心亮点) 只需像聊天一样提问: “2024 年国家发布了哪些药品监管政策?” “A 企业旗下有哪些产品?” “X 药品的不良事件和适应症是什么?” 系统不仅能“听懂”,还能“给对”。 📸 截图示例:在搜索框输入自然语言问题后,下方即时展示智能解析、匹配实体、返回答案。 🔍 实体 / 关系检索 输入任意实体名称即可获取所有相关关系。 📸 截图示例:输入“糖尿病”,界面自动展开所有相关企业、适应症、禁忌等关联节点。 🎯 精确检索(指定数据源 / 数据表 / 字段) 适合结构化抽取后的场景,多用于: 看原字段的抽取结果 数据校对 命中某个具体字段的知识片段 📸 截图示例:选择数据源 → 表名 → 字段后,下方展示精确查询的抽取结果。 📁 批量检索 支持批量导入 ID 文件(如 .txt/.csv),进行自动化查询。 📸 截图示例:批量查询界面支持文件上传、查询任务状态显示、批量结果导出。 🧠 意图识别 提前配置好意图库,例如: 药品功效类 企业关系类 政策解读类 风险事件类 系统会优先识别意图,再匹配知识,极大提升命中率。 📸 截图示例:意图管理页面展示意图库列表、关键词权重,以及对应实体绑定情况。 ➕ 智能推荐 对用户问题进行语义扩展后,给出: 相关知识片段 推荐问答 高相似问题 5️⃣ 适配 ArangoDB,配置级切换图数据库 qKnow 2.1.0 引入通用图数据库抽象层,可以: 使用 Neo4j 使用 ArangoDB 或两者之间自由切换 只需改一个配置文件即可完成切换,无需修改任何代码。 版本亮点 一句话就能搜 —— 支持自然语言的语义检索 各种搜法全都有 —— 批量、精确、实体、关系、意图检索全覆盖 怎么看得清就怎么摆 —— 多布局、多视图任意切换 事件时间线可视化 —— 将事件按时序组织并自动关联实体 图数据库可一键切换 —— Neo4j ↔ ArangoDB 无缝衔接 ✨ 结语 qKnow 2.1.0 不仅是一次版本迭代,更是“知识智能化”方向上的一次跃迁。从管理知识,到理解知识,再到真正让知识参与业务分析和决策,我们正在迈出坚实的一步。 欢迎体验新版,也欢迎向我们反馈使用体验与建议。

优秀的个人博客,低调大师

列式计算处理 K 线数据:Polars 表达式 API 在 A 股分析中的用法

一句话回答: Polars 是以 Rust 实现的列式 DataFrame 库,支持多线程并行和惰性执行。把 QuantDash 取得的 K 线用 pl.from_pandas() 转换后,即可用表达式完成聚合、rolling_mean 滚动窗口和 group_by 多标的分组。它的速度优势主要出现在全市场批量处理中,小数据场景和 pandas 相差不大。转换环节需要 pyarrow,数据口径建议统一为后复权。

资源下载

更多资源
Mario

Mario

马里奥是站在游戏界顶峰的超人气多面角色。马里奥靠吃蘑菇成长,特征是大鼻子、头戴帽子、身穿背带裤,还留着胡子。与他的双胞胎兄弟路易基一起,长年担任任天堂的招牌角色。

腾讯云软件源

腾讯云软件源

为解决软件依赖安装时官方源访问速度慢的问题,腾讯云为一些软件搭建了缓存服务。您可以通过使用腾讯云软件源站来提升依赖包的安装速度。为了方便用户自由搭建服务架构,目前腾讯云软件源站支持公网访问和内网访问。

Rocky Linux

Rocky Linux

Rocky Linux(中文名:洛基)是由Gregory Kurtzer于2020年12月发起的企业级Linux发行版,作为CentOS稳定版停止维护后与RHEL(Red Hat Enterprise Linux)完全兼容的开源替代方案,由社区拥有并管理,支持x86_64、aarch64等架构。其通过重新编译RHEL源代码提供长期稳定性,采用模块化包装和SELinux安全架构,默认包含GNOME桌面环境及XFS文件系统,支持十年生命周期更新。

Sublime Text

Sublime Text

Sublime Text具有漂亮的用户界面和强大的功能,例如代码缩略图,Python的插件,代码段等。还可自定义键绑定,菜单和工具栏。Sublime Text 的主要功能包括:拼写检查,书签,完整的 Python API , Goto 功能,即时项目切换,多选择,多窗口等等。Sublime Text 是一个跨平台的编辑器,同时支持Windows、Linux、Mac OS X等操作系统。

用户登录
用户注册
修改密码
忘记密码