@@ -3,14 +3,19 @@ package com.sfxcode.nosql.mongo
33import java .nio .charset .Charset
44
55import better .files .File
6- import com .sfxcode .nosql .mongo .bson .DocumentHelper
6+ import com .sfxcode .nosql .mongo .bson .{ BsonConverter , DocumentHelper }
77import com .sfxcode .nosql .mongo .database .{ChangeObserver , CollectionStatus , DatabaseProvider }
88import com .sfxcode .nosql .mongo .operation .Crud
99import org .bson .json .JsonParseException
10+ import org .mongodb .scala .model .Aggregates .project
11+ import org .mongodb .scala .model .Projections
1012import org .mongodb .scala .{BulkWriteResult , Document , MongoCollection , Observable , SingleObservable }
1113
1214import scala .collection .mutable .ArrayBuffer
1315import scala .reflect .ClassTag
16+ import org .mongodb .scala .model .Filters ._
17+ import org .mongodb .scala .model .Aggregates ._
18+ import org .mongodb .scala .model .Accumulators ._
1419
1520/**
1621 * Created by tom on 20.01.17.
@@ -32,18 +37,36 @@ abstract class MongoDAO[A](provider: DatabaseProvider, collectionName: String)(i
3237 def collectionStatus : Observable [CollectionStatus ] =
3338 provider.runCommand(Map (" collStats" -> collectionName)).map(document => CollectionStatus (document))
3439
40+ /**
41+ *
42+ * @param sampleSize use sample size greate 0 for better performance on big collections
43+ * @return List of column names
44+ */
45+ def columnNames (sampleSize : Int = 0 ): List [String ] = {
46+ val projectStage = project(Projections .computed(" tempArray" , equal(" $objectToArray" , " $$ROOT" )))
47+ val unwindStage = unwind(" $tempArray" )
48+ val groupStage = group(" _id" , addToSet(" keySet" , " $tempArray.k" ))
49+ val pipeline = {
50+ if (sampleSize > 0 )
51+ List (projectStage, unwindStage, groupStage, sample(sampleSize))
52+ else
53+ List (projectStage, unwindStage, groupStage)
54+ }
55+
56+ val aggregationResult : Document = Raw .findAggregated(pipeline).result()
57+ BsonConverter .fromBson(aggregationResult.get(" keySet" ).head).asInstanceOf [List [String ]]
58+ }
59+
3560 protected def coll : MongoCollection [A ] = collection
3661
3762 // internal object for raw document access
3863 object Raw extends MongoDAO [Document ](provider, collectionName)
3964
4065 def importJsonFile (file : File ): SingleObservable [BulkWriteResult ] = {
4166 val docs = new ArrayBuffer [Document ]()
42- try {
43- if (file.exists) {
44- val iterator = file.lineIterator(Charset .forName(" UTF-8" ))
45- iterator.foreach(line => docs.+= (DocumentHelper .documentFromJsonString(line).get))
46- }
67+ try if (file.exists) {
68+ val iterator = file.lineIterator(Charset .forName(" UTF-8" ))
69+ iterator.foreach(line => docs.+= (DocumentHelper .documentFromJsonString(line).get))
4770 }
4871 catch {
4972 case e : JsonParseException =>
0 commit comments