mongo创建服务器连接及简单查询

1.     Java语言连接mongo库需要mongo提供的驱动包,类似于传统数据库使用的jdbc包。

一般将连接的参数写在配置文件中,这些参数有:

#是否重试

autoConnectRetry=true

#连接池大小

poolSize=50

#主机地址

hosts=ip:port

#数据库名称

dbName=dbname

#数据库连接用户名

userName= username

#连接密码

password=password

#表名称

tableName=emailSent

所以,连接mongoJava代码如下:

import java.util.ArrayList;

import java.util.Properties;

 

import com.mongodb.DB;

import com.mongodb.DBCollection;

import com.mongodb.MongoClient;

import com.mongodb.MongoClientOptions;

import com.mongodb.MongoClientOptions.Builder;

import com.mongodb.ServerAddress;

 

public class MongoDBUtil {

 

         private static final String AUTO_CONNECT_RETRY = "autoConnectRetry";

         private static final String POOL_SIZE = "poolSize";

         private static final String HOSTS = "hosts";

         private static final String DB_NAME = "dbName";

         private static final String USERNAME = "userName";

         private static final String PASSWORD = "password";

         private static final String CONFIG = "ubd_esp_conf.properties";

         private static final Properties prop = new Properties();

         private static MongoClient client = null;

         private static ArrayList<ServerAddress> address = new ArrayList<ServerAddress>();

         private static DB db = null;

        

         static {

                   try{

                            prop.load(MongoDBUtil.class.getClassLoader().getResourceAsStream(CONFIG));

                            //对配置文件中的多个ip地址进行遍历

                            for(String hostIP : prop.getProperty(HOSTS).split(";")){

                                     //虑空

                                     hostIP= hostIP.trim();

                                     //获得ip

                                     Stringip = hostIP.split(":")[0];

                                     //获得端口

                                     int  port= Integer.parseInt(hostIP.split(":")[1]);

                                     //添加地址

                                     address.add(new ServerAddress(ip,port));

                            }

                            mongoDBInit(address);

                   }catch(Exception e){

                            e.getStackTrace();

                   }

         }

        

         /**

          * 初始化MongoDB连接

          * @param address

          * @throws Exception

          */

         private static void mongoDBInit(ArrayList<ServerAddress> address) throws Exception{

                   Builderbuilder = new MongoClientOptions.Builder();

                   builder.autoConnectRetry(Boolean.parseBoolean(prop.getProperty(AUTO_CONNECT_RETRY)));

                   builder.connectionsPerHost(Integer.parseInt(prop.getProperty(POOL_SIZE)));

                   client = new MongoClient(address,builder.build());

                   db = client.getDB(prop.getProperty(DB_NAME));

                   if(!db.isAuthenticated()){

                            if(prop.getProperty(USERNAME)==null||prop.getProperty(PASSWORD)==null){

                                     throw new Exception("the username or password is null in"+CONFIG);

                            }

                            db.authenticate(prop.getProperty(USERNAME), prop.getProperty(PASSWORD).toCharArray());

                   }

         }

        

         /**

          * 返回collection

          * @param tableName

          * @return

          */

         public static DBCollection getCollection(String tableName){

                   return db.getCollection(tableName);

         }

}

2.     给出一个简单的mongo查询示例,将mongo查询的结果写入一个文件,并且按\001分隔,以备接下来使用Hadoop处理。

import java.io.BufferedWriter;

import java.io.File;

import java.io.FileWriter;

import java.io.IOException;

import java.util.Date;

import java.util.Properties;

 

importcom.dangdang.ubd.esp.help.MongoDBUtil;

import com.dangdang.ubd.esp.help.TimeTool;

import com.mongodb.BasicDBObject;

import com.mongodb.DBCollection;

import com.mongodb.DBCursor;

import com.mongodb.DBObject;

import com.mongodb.QueryOperators;

 

public class GetEmailData {

 

   privatestatic final String TABLE_NAME ="tableName";

   privatestatic final String FILE_DIR = "fileDir";

   privatestatic Properties prop = new Properties();

   privatestatic final String CONFIG = "ubd_esp_conf.properties";

   privatestatic int before = 0;

  

   static{

            try{

                     prop.load(GetEmailData.class.getClassLoader().getResourceAsStream(CONFIG));

                     before= Integer.parseInt(prop.getProperty("before"));

            }catch (IOException e) {

                     e.printStackTrace();

            }

   }

  

   publicstatic void getDataToFile(String sDate,String eDate,String tableName,StringfileName){

            //文件

            Filefile = new File(fileName);

           

            if(file.exists()){

                     file.delete();

            }

           

            if(!file.getParentFile().exists()) {

                               file.getParentFile().mkdirs();

                       }

             try {

                       file.createNewFile();

                     }catch (IOException e) {

                        e.printStackTrace();

              }

                      

            BufferedWriterbw = null;

            try{

                     bw= new BufferedWriter(new FileWriter(file));

                     //获取到collection

                     DBCollectiondbCollection = MongoDBUtil.getCollection(tableName);

                    

                     //查询条件为lastChangedTime距离现在为90天以内的并且打开的

                     DBObjectquery = new BasicDBObject();

                     DBObjectcondition = new BasicDBObject();

                     condition.put(QueryOperators.GTE,TimeTool.strToDate(sDate));

                     condition.put(QueryOperators.LT,TimeTool.strToDate(eDate));

                     query.put("lastChangedTime",condition);

                     query.put("open",true);

                    

                     //执行查询

                     DBCursorcursor = dbCollection.find(query);

                     intcount = 0;

                     while(cursor.hasNext()){

                               DBObjectdbObject = cursor.next();

                               Stringinfo = getLineStr(dbObject);

                               bw.write(info);

                               bw.newLine();

                               count++;

                     }

                     bw.flush();

                     System.out.println(count);

            }catch(Exceptione){

                     e.printStackTrace();

            }finally{

                     if(bw!=null){

                               try{

                                        bw.close();

                               }catch (IOException e) {

                                        e.printStackTrace();

                               }

                     }

            }

   }

  

   /**

    * 将mongo查询结果转换成hdfs存放的串

    * @param jsonStr

    * @return

    */

   publicstatic String getLineStr (DBObject jsonStr){

            StringBuffersb = new StringBuffer();

 

            if(jsonStr.containsField("open")){

                     sb.append("\001"+ jsonStr.get("open"));

            }else{

                     sb.append("\001"+ "false");

            }

            if(jsonStr.containsField("openTime")) {

                     sb.append("\001"+ TimeTool.dateToStr((Date)jsonStr.get("openTime")));

            }else{

                     sb.append("\001"+ "1000-00-00 00:00:00");

            }

           

            returnsb.toString();

   }

 

   publicstatic void main(String[] args) {

            try{

                     Stringedate = args[0];

                     Stringsdate = TimeTool.getBeforDate(edate, before);

                     StringtableName = prop.getProperty(TABLE_NAME);

                     StringfileDir = prop.getProperty(FILE_DIR);

                     StringfileName = fileDir+"ubd_esp_email_chg_log";

                     getDataToFile(sdate,edate,tableName,fileName);

            }catch(Exceptione){

                     e.printStackTrace();

                     System.exit(-1);

            }

   }

}

 

### Python连接内网MongoDB和HBase的方法及库 #### 连接内网MongoDB 为了通过Python连接到内网的MongoDB实例,通常会使用`pymongo`库。该库提供了丰富的功能用于管理MongoDB数据库及其文档。 以下是具体的实现方式: 1. **安装依赖** 需要先安装`pymongo`库,可以通过pip命令完成: ```bash pip install pymongo ``` 2. **编写连接代码** 使用`pymongo.MongoClient`类建立与MongoDB连接。假设目标MongoDB运行在本地网络内的某台服务器上(IP地址为`192.168.1.100`),端口默认为`27017`。 下面是一个简单的示例代码片段: ```python from pymongo import MongoClient client = MongoClient('mongodb://192.168.1.100:27017/') # 替换为目标MongoDB IP和端口号[^2] db = client['myDatabase'] # 替换为实际使用的数据库名称 collection = db['myCollection'] # 替换为具体集合名称 document = {"name": "Alice", "age": 30} result = collection.insert_one(document) # 插入一条测试数据 print(f"Inserted ID: {result.inserted_id}") ``` 上述代码展示了如何初始化一个MongoDB客户端并执行基本操作,如插入单条记录。 --- #### 连接内网HBase 对于HBase的支持,推荐使用`happybase`库作为接口层来简化交互过程。 1. **安装依赖** 同样地,需预先安装必要的软件包: ```bash pip install happybase ``` 2. **编写连接代码** 假设HBase服务同样部署在同一局域网下的另一台主机上(例如`192.168.1.200`)。下面是一段典型的程序结构: ```python import happybase connection = happybase.Connection('192.168.1.200') # HBase所在节点的IP地址[^3] table_name = 'test_table' if not table_name.encode() in connection.tables(): families = {'cf1': dict(max_versions=1)} # 定义列族参数 connection.create_table(table_name, families) table = connection.table(table_name) row_key = b'row1' data_to_insert = { b'cf1:name': b'Alice', b'cf1:age': b'30' } table.put(row_key, data_to_insert) # 执行PUT操作存储键值对 retrieved_data = table.row(row_key) print(retrieved_data[b'cf1:name'].decode()) # 输出读取的结果 ``` 此脚本说明了怎样构建至HBase的服务链接,并示范了一些基础动作比如创建表格、写入以及查询指定行的内容。 --- #### 关系型与非关系型数据库对比 值得注意的是,尽管两者都属于持久化存储解决方案范畴,但它们的设计理念存在显著差异。关系型数据库遵循严格的模式定义并通过SQL语句访问资源;而非关系型数据库则更加灵活自由,适合处理大规模分布式场景下海量半结构化或者无固定格式的数据集[^4]。 ---
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值