我有一个我仍在开发的AWS CloudSearch实例。
有时,例如当我对字段的格式进行一些修改时,我发现自己想要清除所有数据并重新生成它。
有没有办法使用控制台清除所有数据,或者我是否需要通过编程手段来解决这个问题?
如果我必须使用编程方法(即生成并发布一堆“删除”SDF文件),有什么好方法可以在CloudSearch实例中查询所有文档吗?
我想我可能只是删除并重新创建实例,但这需要一段时间,并且会丢失所有索引/等级表达式/文本选项等等
答案 0 :(得分:16)
export CS_DOMAIN=https://yoursearchdomain.yourregion.cloudsearch.amazonaws.com
# Get ids of all existing documents, reformat as
# [{ type: "delete", id: "ID" }, ...] using jq
aws cloudsearchdomain search \
--endpoint-url=$CS_DOMAIN \
--size=10000 \
--query-parser=structured \
--search-query="matchall" \
| jq '[.hits.hit[] | {type: "delete", id: .id}]' \
> delete-all.json
# Delete the documents
aws cloudsearchdomain upload-documents \
--endpoint-url=$CS_DOMAIN \
--content-type='application/json' \
--documents=delete-all.json
有关jq的更多信息,请参阅Reshaping JSON with jq
2017年2月22日更新
添加--size
以一次获取最大文档数(10,000)。您可能需要多次重复此脚本。此外,--search-query
可以采取更具体的内容,如果您想要选择删除的文档。
答案 1 :(得分:15)
我能找到的最佳答案有点埋没在AWS文档中。即:
Amazon CloudSearch目前不提供删除机制 域中的所有文档。但是,您可以克隆域 用空域重新开始的配置。更多 信息,请参阅Cloning an Existing Domain's Indexing Options。
来源:http://docs.aws.amazon.com/cloudsearch/latest/developerguide/Troubleshooting.html#ts.cleardomain
答案 2 :(得分:4)
就我而言,我使用了这样的本地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!");
});
}
});
您必须至少知道onface的所有值,才能请求所有ID。在我的代码中,我只放了2个(在 (或....) 部分),但你可以有更多。
完成后,您将使用此命令将一个 delete.json 文件与AWS-CLI一起使用:
aws cloudsearchdomain upload-documents --documents delete.json --content-type application/json --endpoint-url <your CloudSearch endpoint>
......那为我完成了这份工作!
Nekloth
答案 3 :(得分:3)
我一直在使用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'
答案 4 :(得分:2)
您可以将文档批直接直接手动上传到AWS CloudSearch的“仪表板”>“上传文档”。 如果可以枚举要删除的所有索引ID,则可以创建脚本来生成文档批处理或手动生成。
文档批处理格式应为
sample.json
[
{
"type": "delete",
"id": "1"
},
{
"type": "delete",
"id": "2"
}
]
如何枚举所有索引-运行测试搜索
答案 5 :(得分:1)
在PHP上,我设法创建了一个使用AWS PHP SDK清理所有记录的脚本:
clean.php - http://pastebin.com/Lkyk1D1i config.php - http://pastebin.com/kFkZhxCc
您需要在config.php上配置密钥,在clean.php上配置端点,下载AWS PHP SDK,您就可以开始使用了!
请注意,它最多只能清理10000个文件。亚马逊已经有了限制。
答案 6 :(得分:1)
我设法为它创建了PowerShell脚本。在这里查看我的网站:http://www.mpustelak.com/2017/01/aws-cloudsearch-clear-domain-using-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
}
答案 7 :(得分:0)
以下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);
}
}