Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/369.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Amazon web services 如何清除AWS CloudSearch中的所有数据?_Amazon Web Services_Amazon Cloudsearch - Fatal编程技术网

Amazon web services 如何清除AWS CloudSearch中的所有数据?

Amazon web services 如何清除AWS CloudSearch中的所有数据?,amazon-web-services,amazon-cloudsearch,Amazon Web Services,Amazon Cloudsearch,我有一个AWS CloudSearch实例,我仍在开发中 有时,例如当我对字段的格式进行一些修改时,我发现自己想要删除所有数据并重新生成它 是否有任何方法可以使用控制台清除所有数据,或者我必须通过编程方式进行清除 如果我必须使用编程方式(即生成并发布一堆“删除”SDF文件),有没有好的方法可以查询CloudSearch实例中的所有文档 我想我可以删除并重新创建该实例,但这需要一段时间,并且会丢失所有索引/排名表达式/文本选项/etc我能找到的最佳答案多少隐藏在AWS文档中。也就是说: Amazo

我有一个AWS CloudSearch实例,我仍在开发中

有时,例如当我对字段的格式进行一些修改时,我发现自己想要删除所有数据并重新生成它

是否有任何方法可以使用控制台清除所有数据,或者我必须通过编程方式进行清除

如果我必须使用编程方式(即生成并发布一堆“删除”SDF文件),有没有好的方法可以查询CloudSearch实例中的所有文档


我想我可以删除并重新创建该实例,但这需要一段时间,并且会丢失所有索引/排名表达式/文本选项/etc

我能找到的最佳答案多少隐藏在AWS文档中。也就是说:

Amazon CloudSearch目前不提供删除机制 域中的所有文档。但是,您可以克隆域 使用空域重新开始的配置。更多 有关详细信息,请参阅


来源:

我一直在做以下工作,使用python适配器boto清空cloudsearch。不漂亮,但它完成了任务。困难的部分是平衡您获取的数量是否在cloudsearch 5mb限制内

    count = CloudSearchAdaptor.Instance().get_total_documents()
    while count > 0:
         results = CloudSearchAdaptor.Instance().search("lolzcat|-lolzcat", 'simple', 1000)
         for doc in results.docs:
             CloudSearchAdaptor.Instance().delete(doc['id'])

         CloudSearchAdaptor.Instance().commit()
         #add delay here if cloudsearch takes to long to propigate delete change            
         count = CloudSearchAdaptor.Instance().get_total_documents()
Cloudsearch适配器类如下所示:

from boto.cloudsearch2.layer2 import Layer2
from singleton import Singleton

@Singleton
class CloudSearchAdaptor:

    def __init__(self):
        layer2 = Layer2(
            aws_access_key_id='AWS_ACCESS_KEY_ID',
            aws_secret_access_key='AWS_SECRET_ACCESS_KEY',
            region='AWS_REGION'
        )
        self.domain = layer2.lookup('AWS_DOMAIN'))
        self.doc_service = self.domain.get_document_service()
        self.search_service = self.domain.get_search_service()

@staticmethod
def delete(id):
    instance = CloudSearchAdaptor.Instance()
    try:
        response = instance.doc_service.delete(id)
    except Exception as e:
        print 'Error deleting to CloudSearch'

@staticmethod
def search(query, parser='structured', size=1000):
    instance = CloudSearchAdaptor.Instance()
    try:
        results = instance.search_service.search(q=query, parser=parser, size=size)
        return results
    except Exception as e:
        print 'Error searching CloudSearch'

@staticmethod
def get_total_documents():
    instance = CloudSearchAdaptor.Instance()
    try:
        results = instance.search_service.search(q='matchall', parser='structured', size=0)
        return results.hits
    except Exception as e:
        print 'Error getting total documents from CloudSearch'

@staticmethod
def commit():
    try:
        response = CloudSearchAdaptor.Instance().doc_service.commit()
        CloudSearchAdaptor.Instance().doc_service.clear_sdf()
    except Exception as e:
        print 'Error committing to CloudSearch'

在PHP上,我使用AWS PHP SDK创建了一个用于清理所有记录的脚本:

clean.php- config.php-

你需要在config.php上配置你的密钥,在clean.php上配置你的端点,下载AWS php SDK,你就可以开始了


注意,它最多只能清理10000个文档,因为Amazon有一个限制。

在我这边,我使用了一个本地nodejs脚本,如下所示:

var AWS = require('aws-sdk');

AWS.config.update({
    accessKeyId: '<your AccessKey>', 
    secretAccessKey: '<Your secretAccessKey>',
    region: '<your region>',
    endpoint: '<your CloudSearch endpoint'
});

var params = {
       query:"(or <your facet.FIELD:'<one facet value>' facet.FIELD:'<one facet value>')",
       queryParser:'structured'
};


var cloudsearchdomain = new AWS.CloudSearchDomain(params);
cloudsearchdomain.search(params, function(err, data) {
    var fs = require('fs');
    var result = [];
    if (err) {
        console.log("Failed");
        console.log(err);
    } else {
        resultMessage = data;
        for(var i=0;i<data.hits.hit.length;i++){
            result.push({"type":"delete","id":data.hits.hit[i].id});
        }    

        fs.writeFile("delete.json", JSON.stringify(result), function(err) {
            if(err) {return console.log(err);}
        console.log("The file was saved!");
        });
    }
});
var AWS=require('AWS-sdk');
AWS.config.update({
accessKeyId:“”,
secretAccessKey:“”,
区域:“”,

端点:'Java版本,以清除云搜索域中的所有数据:

private static final AmazonCloudSearchDomain cloudSearch = Region
        .getRegion(Regions.fromName(CommonConfiguration.REGION_NAME))
        .createClient(AmazonCloudSearchDomainClient.class, null, null)
        .withEndpoint(CommonConfiguration.SEARCH_DOMAIN_DOCUMENT_ENDPOINT);

public static void main(String[] args) {

    // retrieve all documents from cloud search
    SearchRequest searchRequest = new SearchRequest().withQuery("matchall").withQueryParser(QueryParser.Structured);
    Hits hits = cloudSearch.search(searchRequest).getHits();

    if (hits.getFound() != 0) {
        StringBuffer sb = new StringBuffer();
        sb.append("[");

        int i = 1;
        // construct JSON to delete all
        for (Hit hit : hits.getHit()) {
            sb.append("{\"type\": \"delete\",  \"id\": \"").append(hit.getId()).append("\"}");
            if (i < hits.getHit().size()) {
                sb.append(",");
            }
            i++;
        }

        sb.append("]");

        // send to cloud search
        InputStream documents = IOUtils.toInputStream(sb.toString());
        UploadDocumentsRequest uploadDocumentsRequest = new UploadDocumentsRequest()
                .withContentType("application/json").withDocuments(documents).withContentLength((long) sb.length());
        cloudSearch.uploadDocuments(uploadDocumentsRequest);
    }
}
private static final AmazonCloudSearchDomain cloudSearch=区域
.getRegion(Regions.fromName(CommonConfiguration.REGION\u NAME))
.createClient(AmazonCloudSearchDomainClient.class,null,null)
.withEndpoint(CommonConfiguration.SEARCH\u DOMAIN\u DOCUMENT\u ENDPOINT);
公共静态void main(字符串[]args){
//从云搜索检索所有文档
SearchRequest SearchRequest=new SearchRequest().withQuery(“matchall”).withQueryParser(QueryParser.Structured);
Hits Hits=cloudSearch.search(searchRequest).getHits();
如果(hits.getFound()!=0){
StringBuffer sb=新的StringBuffer();
某人加上(“[”);
int i=1;
//构造JSON以删除所有
for(Hit-Hit:hits.getHit()){
sb.append(“{\”type\”:“delete\”,“id\”:\”).append(hit.getId()).append(“\”);
如果(i
使用命令行和从命令行(在mac上使用bash进行测试):

导出CS\u域=https://yoursearchdomain.yourregion.cloudsearch.amazonaws.com
#获取所有现有文档的ID,格式为
#[{type:“delete”,id:“id”},…]使用jq
aws cloudsearchdomain搜索\
--端点url=$CS\u域\
--尺寸=10000\
--查询解析器=结构化\
--搜索查询=“匹配所有”\
|jq'[.hits.hit[]|{type:“delete”,id:.id}'\
>delete-all.json
#删除文件
aws cloudsearchdomain上载文档\
--端点url=$CS\u域\
--content type='application/json'\
--documents=delete-all.json
有关jq的更多信息,请参阅

2017年2月22日更新


添加了
--size
以获取最大文档数(10000)一次。您可能需要多次重复此脚本。此外,
--search query
可以采取更具体的操作,如果您希望对删除的文档进行选择。

我已为其创建了PowerShell脚本。请查看我的网站:

脚本:

$searchUrl = '[SEARCH_URL]'
$documentUrl = '[DOCUMENT_URL]'
$parser = 'Lucene'
$querySize = 500

function Get-DomainHits()
{
    (Search-CSDDocuments -ServiceUrl $searchUrl -Query "*:*" -QueryParser $parser -Size $querySize).Hits;
}

function Get-TotalDocuments()
{
    (Get-DomainHits).Found
}

function Delete-Documents()
{
    (Get-DomainHits).Hit | ForEach-Object -begin { $batch = '[' } -process { $batch += '{"type":"delete","id":' + $_.id + '},'} -end { $batch = $batch.Remove($batch.Length - 1, 1); $batch += ']' }

    Try
    {
        Invoke-WebRequest -Uri $documentUrl -Method POST -Body $batch -ContentType 'application/json'
    }
    Catch
    {
        $_.Exception
        $_.Exception.Message
    }
}

$total = Get-TotalDocuments
while($total -ne 0)
{
    Delete-Documents

    $total = Get-TotalDocuments

    Write-Host 'Documents left:'$total
    # Sleep for 1 second to give CS time to delete documents
    sleep 1
}

您可以手动将文档批直接上传到AWS CloudSearch,Dashboard>upload document。 如果可以枚举所有要删除的索引id,则可以创建脚本以生成文档批处理或手动生成

文档批处理格式应如下所示

sample.json

[
    {
        "type": "delete",
        "id": "1"
    },
    {
        "type": "delete",
        "id": "2"
    }
]
如何枚举所有索引-运行测试搜索

  • 搜索:id:*(或您确定所有人都可以使用的任何字段)
  • 查询解析器:Lucene

创建一个脚本来创建包含所有参数的搜索域Sigh;希望他们能添加这样做的方法。我喜欢在意外情况下单击做坏事的按钮!同意此功能应该更简单。此外,您的链接似乎不再包含任何有关克隆域的信息……但我在–unfortun找到了此信息对于我来说,这个过程无限期地挂起,除了已经不理想之外,因为我必须跟踪对端点的所有引用以进行更新。而且它现在似乎完全消失了。因此,这个答案似乎不再是答案。它消失了…=/如果您有必填字段,查询可能会更有效率(在我的例子中是应用程序名称。然后,它将是
查询:“(不是应用程序名称:”)
谢谢,这非常有效。我必须将size参数添加到搜索中以获取我的所有文档。re's a bash脚本使用@kevin tonon的答案,并添加循环以及状态输出,告诉您有多少文档:
[
    {
        "type": "delete",
        "id": "1"
    },
    {
        "type": "delete",
        "id": "2"
    }
]