Geomesa集成HBase:Geotools DataStore API 读写 HBase

本文介绍了如何利用Geomesa与HBase进行集成,通过GeoTools的DataStore API实现对HBase的读写操作,探讨了相关依赖和配置过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >


import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.Options;
import org.apache.commons.cli.ParseException;
import org.apache.commons.lang.StringUtils;
import org.apache.hadoop.hbase.HColumnDescriptor;
import org.apache.hadoop.hbase.HTableDescriptor;
import org.apache.hadoop.hbase.TableName;
import org.apache.hadoop.hbase.client.Admin;
import org.apache.hadoop.hbase.client.Connection;
import org.geotools.data.*;
import org.geotools.factory.Hints;
import org.geotools.feature.simple.SimpleFeatureBuilder;
import org.geotools.filter.identity.FeatureIdImpl;
import org.geotools.filter.text.cql2.CQLException;
import org.geotools.filter.text.ecql.ECQL;
import org.locationtech.geomesa.hbase.data.HBaseDataStore;
import org.locationtech.geomesa.hbase.data.HBaseDataStoreFactory;
import org.locationtech.geomesa.hbase.data.HBaseFeatureWriter;
import org.locationtech.geomesa.index.metadata.GeoMesaMetadata;
import org.opengis.feature.Property;
import org.opengis.feature.simple.SimpleFeature;
import org.opengis.feature.simple.SimpleFeatureType;
import org.opengis.feature.type.Name;
import org.opengis.filter.Filter;
import org.opengis.filter.sort.SortBy;

import java.io.IOException;
import java.util.*;

/**
 * @Author: gh
 * @Description: 通过geomesa操作hbase数据。
 * 1.新增:通过geomesa封装并存储数据到HBase。
 * //geomesa默认主键名称是__fid__
 * SimpleFeature封装的数据中,主键是feature ID(__fid__),不是数据自身的ID(gid,fid等)。
 * 2.删除:根据rowkey删除数条记录。
 * 3.更新:更新除geom以外的字段。
 * 和新增使用同一个方法。
 * 4.查询:解析出所有字段并返回;分页;模糊查询。
 * 条件查询、模糊查询
 */
public class GeomesaHBaseImpl extends HBaseDaoImpl{


    public GeomesaHBaseImpl(DataBaseDTO dto){
        super(dto);
    }
    /**
     * 精确查询、模糊查询
     * @param tableName 表名
     * @param qualifier 字段名
     * @param fieldValue 字段值
     * @param pageSize 分页大小
     * @param pageNum 当前页码
     * @return
     */
    public Map<String,Object> queryByRandomField(String tableName, String qualifier,String fieldValue,
                                           Integer pageSize,Integer pageNum) {
        Query query = null;
        DataStore ds = createDataStore(tableName);
        if(ds != null){
            //设置查询条件
            try {
                query = new Query(getTypeNames(ds)[0],
                        ECQL.toFilter(qualifier+" LIKE '%"+fieldValue+"%'"));
            } catch (CQLException e) {
                e.printStackTrace();
            }
        }
        return queryFeatureDatas(ds, query,pageSize,pageNum);
    }

    /**
     * 统计一个表中的记录总条数
     * 【注意:不能直接调用父类中的totalCount方法,统计结果不对!】
     * @param tableName 表名
     * @return 总条数
     */
    public long totalCount2(String tableName) {
        long count = 0;
        try {
            //不设置查询条件
            String indexTable = getXZ3IndexTable(tableName);
            //使用协处理器统计(任何一张)索引表才有结果。
            count = super.totalCount(indexTable);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return count;
       /* DataStore ds = createDataStore(tableName);
        Query query = new Query(getTypeNames(ds)[0]);
        return getTotalCountByQuery(ds,query);*/
    }
    /**
     * 获取模糊查询
     * @param tableName 表名
     * @param qualifier 字段名
     * @param fieldValue 字段值
     * @return 模糊查询的结果总数
     */
    public long totalCountOfFuzzyQuery(String tableName,String qualifier,String fieldValue) {
        long count = 0;
        Query query = null;
        DataStore ds = createDataStore(tableName);
        if(ds != null){
            //设置查询条件
            try {
                query = new Query(getTypeNames(ds)[0],
                        ECQL.toFilter(qualifier+" LIKE '%"+fieldValue+"%'"));
            } catch (CQLException e) {
                e.printStackTrace();
            }
            count =  getTotalCountByQuery(ds, query);
        }
        return count;
    }
    /**
     * 分页查询。
     * @param tableName 表名
     * @param pageSize 每页的大小
     * @param pageNum  当前页的页数
     */
    public Map<String,Object> getAllRowsByPage(String tableName, Integer pageSize, Integer pageNum) {
        //不设置查询条件
        DataStore ds = createDataStore(tableName);
        Query query = null;
        if(ds != null){
            query = new Query(getTypeNames(ds)[0]);
        }
        return  queryFeatureDatas(ds, query,pageSize,pageNum);
    }
    /**
     * 获取指定命名空间(数据库)下所有的表的名称。
     * (排除元数据表)
     * 源码中createSchema时命名表:GeoMesaFeatureIndex
     * .formatTableName(ds.config.catalog, GeoMesaFeatureIndex.tableSuffix(this, partition), sft)
     * @param nameSpace
     * @return
     */
    @Override
    public List<String> getTablenamesOfDB(String nameSpace) {
        //过滤掉了disable的表
        List<String> fullTableNames = getFullTablenamesOfDB(nameSpace);
        List<String> filteredTableNames = new ArrayList<>();
        for (String fullName : fullTableNames) {
            List<String> cfs = getColumnFamilies(fullName);
            //catalog表的CF=m,索引表的CF=d
            if(cfs.contains("m")){
                fullName = fullName.contains(":") ? fullName.split(":")[1] : fullName;
                filteredTableNames.add(fullName);
            }
           /* DataStore ds = createDataStore(fullName);
        //当fullname是索引表时,datastore=null,此时报错:NoSuchColumnFamilyException/RemoteWithExtrasException。
            if(ds != null){
                fullName = fullName.contains(":") ? fullName.split(":")[1] : fullName;
                filteredTableNames.add(fullName);
            }*/
        }
        return filteredTableNames;
    }
    /**
     * 获取某张表的字段名称和字段类型。
     * @param tableName 表的名称
     * @return map:key字段名称,value字段类型的class字符串。
     */
    @Override
    public Map<String, String> getColumnNames(String tableName) {
        DataStore dataStore = createDataStore(tableName);
        return getColumnNames(dataStore);
    }

    /**
     * 新增/更新一条数据。
     * 【注意:新增的数据中不包括主键属性RowKey!主键的设置为后台自动生成!】
     * 【注意:更新的数据中要包括主键属性RowKey!】
     * @param tableName 表名
     * @param qualifiers 字段名
     * @param values 字段值
     * @return 插入的数据条数
     */
    public int insert(String tableName, String []qualifiers, String []values) {
        DataStore ds = createDataStore(tableName);
        if(ds != null){
            SimpleFeatureType sft = getSimpleFeatureType(ds);
            //组织数据
            if(qualifiers!=null && values!=null){
                int len1 = qualifiers.length;
                int len2 = values.length;
                if(len1==len2){
                    //查询表中的字段,确定主键
                /*Query query = new Query(getTypeNames(ds)[0]);
                Map<String, Object> queryMap = queryFeatureDatas(ds, query, 1, 1);
                String pk = queryMap.get("pk").toString();*/
                    //封装数据
                    List<Map<String,Object>> datas = new ArrayList<>();
                    Map<String,Object> map = new HashMap<>();
                    for(int i=0;i<len1;i++){
                        map.put(qualifiers[i], values[i]);
                    }
                    datas.add(map);
                    List<SimpleFeature> simpleFeatures = dataToSimpleFeatures(sft,datas);
                    return writeFeatures(ds, sft, simpleFeatures);
                }
            }
        }
        return 0;
    }

    /**
     * 根据指定的条件,删除一条或多条满足条件的数据。
     * 【注意:一般使用主键进行精确删除!!】
     * @param tableName
     * @param fieldValues 字段名称和值
     * @return 删除的数据条数
     */
    public int deleteRecords(String tableName, Map<String,Object> fieldValues) {
        int count = 0;
        DataStore ds = createDataStore(tableName);
        if(ds == null){
            return count;
        }
        if(fieldValues != null){
            List<Query> queries = new ArrayList<>();
            //获取全称的表名
            tableName = super.getFullTableName(tableName);
            //根据字段名称和值,构建查询条件
            Set<Map.Entry<String, Object>> entries = fieldValues.entrySet();
            for (Map.Entry<String, Object> entry : entries) {
                String field = entry.getKey();
                Object value = entry.getValue();
                try {
                    Filter filter = ECQL.toFilter(field + " = '" + value.toString() + "'");
                    queries.add(new Query(tableName, filter));
                } catch (CQLException e) {
                    e.printStackTrace();
                }
            }
            //根据查询条件,查询对应的features
            List<SimpleFeature> simpleFeatures = queryFeatures(ds, queries);
            //删除指定的features记录
            String typeName = getTypeNames(ds)[0];
            count = removeFeatures(ds, typeName, simpleFeatures);
        }
        return count;
    }

    /**
     * 查询某个命名空间下的若干个表的总计大小。
     * @param nameSpace 命名空间
     * @param tables 表的名称
     * @param unit 大小单位
     * @return 总计打下。
     */
    @Override
    public double storeSizeOfTbl(String nameSpace,String[] tables, SizeUnitEnum unit) {
        boolean flag = isNamespaceExist(nameSpace);
        List<String> allGivenTables = new ArrayList<>();
        if(flag && tables != null){
            for (String table : tables) {
                //搜索出指定tables相关的元数据表
                List<String> associatedMetaTables = getAssociatedMetaTables(table);
                allGivenTables.addAll(associatedMetaTables);
            }
        }
        String[] tableNamesArray = allGivenTables.toArray(new String[allGivenTables.size()]);
        return super.storeSizeOfTbl(nameSpace,tableNamesArray, unit);
    }
    private boolean checkTableEnabled(Connection conn, String tableName){
        try {
            String fullTableName = super.getFullTableName(tableName);
            TableName tn = TableName.valueOf(fullTableName);
            return conn.getAdmin().isTableEnabled(tn);
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }
    /**
     * 删除若干条feature数据。
     * @param datastore
     * @param typeName feature type name
     * @param features 封装的需要删除的数据列表
     * @return 删除的条数
     */
    private int removeFeatures(DataStore datastore,String typeName,List<SimpleFeature> features){
        int count = 0;
        if(datastore == null){
            return count;
        }
        try (FeatureWriter<SimpleFeatureType, SimpleFeature> writer =
                     datastore.getFeatureWriter(typeName, Transaction.AUTO_COMMIT)) {
                HBaseFeatureWriter hbaseWriter = (HBaseFeatureWriter)writer;
            for (SimpleFeature feature : features) {
                hbaseWriter.removeFeature(feature);
                /* 以下方式行不通,数据并没有被删除:
                SimpleFeature next = writer.next();
                next = feature;
                writer.remove();*/
                //next.setAttributes(feature.getAttributes());
                count+=1;
            }
        }catch(IOException e){
            System.out.println(e.getMessage());
        }catch (NullPointerException e){
            System.out.println(e.getMessage());
        }
        System.out.println("Delete "+count+" features successfully!");
        return count;
    }
    /**
     * 写入feature数据
     * @param datastore
     * @param sft
     * @param features 封装的数据列表
     * @return 写入的条数
     */
    private int writeFeatures(DataStore datastore,SimpleFeatureType sft,List<SimpleFeature> features){
        int count = 0;
        if(datastore == null){
            return count;
        }
        try (FeatureWriter<SimpleFeatureType, SimpleFeature> writer =
                     datastore.getFeatureWriterAppend(sft.getTypeName(), Transaction.AUTO_COMMIT)) {
            for (SimpleFeature feature : features) {
                // 使用geotools writer,获取一个feature,然后修改并提交。
                // appending writers will always return 'false' for haveNext, so we don't need to bother checking
                SimpleFeature toWrite = writer.next();
                // copy attributes:
                List<Object> attributes = feature.getAttributes();
                toWrite.setAttributes(attributes);
                // 如果设置了 feature ID, 需要转换为实现类,并添加USE_PROVIDED_FID hint到user data
                String featureId = feature.getID();
                ((FeatureIdImpl) toWrite.getIdentifier()).setID(featureId);
                //toWrite.getUserData().put(Hints.USE_PROVIDED_FID, Boolean.TRUE);
                // 或者可直接使用 PROVIDED_FID hint
                toWrite.getUserData().put(Hints.PROVIDED_FID, featureId);
                //如果没有设置feature ID, 会自动生成一个UUID
                toWrite.getUserData().putAll(feature.getUserData());
                // write the feature
                writer.write();
                count += 1;
            }
        }catch(IOException e){
            System.out.println(e.getMessage());
        }catch (NullPointerException e){
            System.out.println(e.getMessage());
        }
        System.out.println("Write "+count+" features successfully!");
        return count;
    }

    /**
     * 将数据封装到SimpleFeature,一行数据就是一个SimpleFeature。
     * @param sft feature类型信息
     * @param datas 多行数据值。map中的key是字段名,value是字段值。
     *              【注意数据中不包括主键!】
     * @return 多行数据组成的SimpleFeature对象列表。
     */
    private List<SimpleFeature> dataToSimpleFeatures(SimpleFeatureType sft,
                                                      List<Map<String,Object>> datas) {
        List<SimpleFeature> features = new ArrayList<>();
        //查看user data设置
        /*Map<Object, Object> userDatas = sft.getUserData();
        Boolean idProvided = (Boolean)userDatas.get(Hints.USE_PROVIDED_FID);
        idProvided = idProvided == null?Boolean.FALSE:idProvided;*/
        //使用geotools SimpleFeatureBuilder创建特征features
        SimpleFeatureBuilder builder = new SimpleFeatureBuilder(sft);
        for (Map<String, Object> rowMap : datas) {
            Set<String> fieldNames = rowMap.keySet();
            //设置feature id
            String featureId = null;
            if(fieldNames.contains(pk)){
                featureId = rowMap.get(pk).toString();
                fieldNames.remove(pk);
            }else{
                //新增时,自动生成feature id。
                featureId = UUID.randomUUID().toString();
            }
            SimpleFeature feature = null;
            for (String fieldName : fieldNames) {
                Object fieldValue = rowMap.get(fieldName);
                //写入数据
                builder.set(fieldName, fieldValue);
                //确定是否需要自己提供ID
               /* if(idProvided){
                    //使用自己提供的ID
                    featureId = UUID.randomUUID().toString();
                }*/
            }
            try {
                // 告知geotools,我们要使用自己提供的ID
                builder.featureUserData(Hints.USE_PROVIDED_FID, Boolean.TRUE);
                // build the feature - this also resets the feature builder for the next entry
                // 一律使用自己提供的ID!
                feature = builder.buildFeature(featureId);
                features.add(feature);
            } catch (Exception e) {
                System.out.println("Invalid SimpleFeature data: " + e.toString());
            }
        }
        return Collections.unmodifiableList(features);
    }
    private Map<String, String> buildParams(String tableName) throws ParseException {
        System.out.println("Start building parameters...");
        String zk = dataBaseDTO.getIp()+":"+dataBaseDTO.getHost();
        String[]args = new String[]{"--hbas
### 回答1: Geomesa可以很方便地集成HBase和Spark,实现对HBase读写操作。具体步骤如下: 1. 首先需要在HBase中创建表,可以使用HBase shell或者HBase API进行创建。 2. 在Spark中引入Geomesa的依赖,可以使用Maven或者SBT进行引入。 3. 使用Geomesa提供的HBaseDataStoreFactory创建HBaseDataStore对象,连接到HBase中的表。 4. 使用Spark的API读取HBase中的数据,可以使用RDD或者DataFrame进行读取。 5. 使用Geomesa提供的HBaseFeatureWriter将数据写入到HBase中。 需要注意的是,在使用Geomesa进行读写HBase时,需要使用Geomesa提供的SimpleFeature类型进行操作。同时,需要在HBase中创建相应的列族和列,以存储SimpleFeature对象的属性值。 ### 回答2: Geomesa是一个基于地理空间数据管理和分析的开源工具。它集成HBase和Spark,可以实现读写HBase的功能。 在Geomesa中,HBase作为数据存储和查询的主要工具,Spark则用于并行计算和数据处理。通过这种方式,HBase可以实现大规模的数据存储和高效的数据查询,而Spark可以进行并行计算和数据处理,提高数据分析的效率。 在使用Geomesa集成HBase和Spark进行读写HBase的时候,需要进行以下操作: 1. 配置HBase和Spark的环境:为了保证Geomesa正常运作,需要正确配置HBase和Spark的环境。具体的配置方式可以参考Geomesa的官方文档。 2. 读写HBase数据:通过GeomesaAPI,可以实现对HBase数据的读写操作。其中,读操作可以通过Scan类进行,而写操作可以通过Put和Delete类进行。 3. 创建和管理数据表:在Geomesa中,可以通过SimpleFeatureType类来定义数据表结构,并且可以使用Spark和HBaseAPI来实现数据表的创建和管理。 4. 进行空间查询和空间分析:Geomesa支持空间查询和空间分析的功能,可以通过Spark和HBaseAPI来实现。 以上就是使用Geomesa集成HBase和Spark进行读写HBase的基本操作流程。通过这种方式,可以实现高效、灵活、可扩展的地理空间数据处理和分析,为地理信息系统的应用提供了强有力的支持。 ### 回答3: geomesa是一个基于Apache Spark和Apache Accumulo的开源地理空间数据分析框架。它提供了丰富的地理空间分析功能,并支持海量地理数据的处理。随着geomesa社区的发展,它也开始支持其他的后端存储引擎,例如HBasegeomesa集成HBase和Spark的主要目的是为了在HBase中存储和查询大规模地理数据,并通过Spark进行批量计算和实时分析。这种集成方式可以实现高效的数据处理和快速的响应时间,尤其适用于对海量地理数据进行地理空间分析和挖掘的场景。 在geomesa中使用HBase的过程主要包括以下几个步骤: 1. 安装HBase和Spark 在使用geomesa之前,需要先安装和配置HBase和Spark环境。HBase是一个开源分布式数据库,可以存储和管理大量的结构化数据;Spark是一个快速的大数据处理引擎,可以进行批量计算和实时分析。 2. 安装geomesa geomesa是一个基于Spark和Accumulo的地理空间分析框架,可以在Spark中快速地进行大规模地理数据的处理和分析。安装geomesa的过程很简单,只需要下载并解压缩geomesa的安装文件即可。 3. 创建HBase数据表 在使用geomesa之前,需要先在HBase中创建相应的数据表。通常情况下,geomesa会为每个表创建两个列族,一个是属性列(attributes),用于存储地理对象的属性信息;另一个是空间列(spatial),用于存储地理对象的空间信息。 4. 使用geomesa创建地理数据集 在HBase中创建好数据表之后,需要使用geomesa创建相应的地理数据集(SimpleFeatureType)。geomesa提供了多种不同类型的SimpleFeatureType,可以根据实际需求选择相应的类型。 5. 将地理数据写入HBase 将地理数据写入HBase的过程很简单,只需要借助geomesa提供的API即可。geomesa支持将地理数据写入HBase和从HBase中读取地理数据。写入数据时,需要指定相应的地理数据集和HBase表,geomesa会自动将数据按照指定的格式写入HBase。 6. 从HBase中读取地理数据 从HBase中读取地理数据的过程同样也很简单,只需要借助geomesa提供的API即可。读取数据时,需要指定相应的地理数据集和HBase表,geomesa会自动从HBase中读取数据,并将数据以相应的格式返回。 以上就是geomesa集成HBase和Spark读写HBase的主要步骤,通过这种方式可以实现高效的海量地理数据处理和分析。但在实际应用中,还需要考虑数据安全、性能优化等方面的问题。因此,在使用geomesa时需要根据实际需求进行相应的优化和配置。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值